<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

// Use a namespace when registering by prepending the
// package's name to the op’s name and separate with a '>'.
// This is the recommendation for out-of-tree ops to avoid name collisions in
// "Best practices for custom operations in TensorFlow"
// https://github.com/tensorflow/community/blob/master/rfcs/20190726-custom-ops.md

REGISTER_OP("Examples>MultiplexSparse")
    .Input("cond_indices: int64")
    .Input("cond_values: bool")
    .Input("cond_shape: int64")
    .Input("a_indices: int64")
    .Input("a_values: T")
    .Input("a_shape: int64")
    .Input("b_indices: int64")
    .Input("b_values: T")
    .Input("b_shape: int64")
    .Output("output_indices: int64")
    .Output("output_values: T")
    .Output("output_shape: int64")
    .Attr("T: type")
    .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) {
      tensorflow::shape_inference::ShapeHandle unused;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &unused));  // cond_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &unused));  // cond_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &unused));  // cond_shape
      TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &unused));  // a_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 1, &unused));  // a_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(5), 1, &unused));  // a_shape
      TF_RETURN_IF_ERROR(c->WithRank(c->input(6), 2, &unused));  // b_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(7), 1, &unused));  // b_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(8), 1, &unused));  // b_shape
      const auto num_rows = c->UnknownDim();
      const auto dense_rank = c->UnknownDim();
      c->set_output(0, c->Matrix(num_rows, dense_rank));
      c->set_output(1, c->Vector(num_rows));
      c->set_output(2, c->Vector(dense_rank));
      return tensorflow::Status::OK();
    })
    .Doc(R"doc(
Return elements chosen from `a` or `b` depending on `cond`.

This is similar to `np.where` and `tf.where`, but simplified to only handle
the case of sparse tensors that are vectors, no optional parameters,
no broadcasting, etc.. Elements for `a` are chosen if there is a `true` `cond`
value at the same positon. Elements for `a` are chosen if there is not a `true`
`cond` value at the same positon, i.e., if either there is a `false` `cond` value
or the `cond` value is not specified.

Indices must be ordered as described by tf.sparse_reorder.

cond_indices: a rank-2 tensor of sparse indices.
cond_values: a rank-1 tensor of sparse values.
cond_shape: a rank-1 tensor representing the dense shape.
a_indices: a rank-2 tensor of sparse indices.
a_values: a rank-1 tensor of sparse values.
a_shape: a rank-1 tensor representing the dense shape.
b_indices: a rank-2 tensor of sparse indices.
b_values: a rank-1 tensor of sparse values.
b_shape: a rank-1 tensor representing the dense shape.
output_indices: a rank-2 tensor of sparse indices.
output_values: a rank-1 tensor of sparse values.
output_shape: a rank-1 tensor representing the dense shape.
)doc");
<commit_msg>fix docstring for multiplex_3 custom op example<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

// Use a namespace when registering by prepending the
// package's name to the op’s name and separate with a '>'.
// This is the recommendation for out-of-tree ops to avoid name collisions in
// "Best practices for custom operations in TensorFlow"
// https://github.com/tensorflow/community/blob/master/rfcs/20190726-custom-ops.md

REGISTER_OP("Examples>MultiplexSparse")
    .Input("cond_indices: int64")
    .Input("cond_values: bool")
    .Input("cond_shape: int64")
    .Input("a_indices: int64")
    .Input("a_values: T")
    .Input("a_shape: int64")
    .Input("b_indices: int64")
    .Input("b_values: T")
    .Input("b_shape: int64")
    .Output("output_indices: int64")
    .Output("output_values: T")
    .Output("output_shape: int64")
    .Attr("T: type")
    .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) {
      tensorflow::shape_inference::ShapeHandle unused;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &unused));  // cond_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &unused));  // cond_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &unused));  // cond_shape
      TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &unused));  // a_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 1, &unused));  // a_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(5), 1, &unused));  // a_shape
      TF_RETURN_IF_ERROR(c->WithRank(c->input(6), 2, &unused));  // b_indices
      TF_RETURN_IF_ERROR(c->WithRank(c->input(7), 1, &unused));  // b_values
      TF_RETURN_IF_ERROR(c->WithRank(c->input(8), 1, &unused));  // b_shape
      const auto num_rows = c->UnknownDim();
      const auto dense_rank = c->UnknownDim();
      c->set_output(0, c->Matrix(num_rows, dense_rank));
      c->set_output(1, c->Vector(num_rows));
      c->set_output(2, c->Vector(dense_rank));
      return tensorflow::Status::OK();
    })
    .Doc(R"doc(
Return elements chosen from `a` or `b` depending on `cond`.

This is similar to `np.where` and `tf.where`, but simplified to only handle
the case of sparse tensors that are vectors, no optional parameters,
no broadcasting, etc.. Elements for `a` are chosen if there is a `true` `cond`
value at the same position. Elements for `b` are chosen if there is not a `true`
`cond` value at the same position, i.e., if either there is a `false` `cond`
value or the `cond` value is not specified.

Indices must be ordered as described by tf.sparse_reorder.

cond_indices: a rank-2 tensor of sparse indices.
cond_values: a rank-1 tensor of sparse values.
cond_shape: a rank-1 tensor representing the dense shape.
a_indices: a rank-2 tensor of sparse indices.
a_values: a rank-1 tensor of sparse values.
a_shape: a rank-1 tensor representing the dense shape.
b_indices: a rank-2 tensor of sparse indices.
b_values: a rank-1 tensor of sparse values.
b_shape: a rank-1 tensor representing the dense shape.
output_indices: a rank-2 tensor of sparse indices.
output_values: a rank-1 tensor of sparse values.
output_shape: a rank-1 tensor representing the dense shape.
)doc");
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <csignal>
#include <iomanip>
#include <exception>

#include "common/util.h"
#include "common/cxxopts.h"
#include "param_util.h"
#include "cynder.h"
#include "pitcher.h"
#include "chella.h"
#include "quid.h"

static bool interrupted = false;
static std::vector<IModule *> moduleList;
static IModule *currentModule = nullptr;

void signal_handler(int signum) {
	interrupted = true;
}

static void catch_signals() {
	struct sigaction action;
	action.sa_handler = signal_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGTERM, &action, NULL);
}

struct UnknownModule : public std::exception {
	const char *what() const throw () {
		return "Unknown module";
	}
};

static void runModuleCommand(const std::string& commandline) {
	std::stringstream ss;
	ss.str(commandline);
	std::string command;
	std::vector<std::string> argv;

	if (!currentModule)
		throw UnknownCommand();

	std::string item;
	while (std::getline(ss, item, ' ')) {
		if (command.empty()) {
			command = item;
			continue;
		}

		argv.push_back(item);
	}

	try {
		currentModule->exec(command, argv);
	} catch (TooFewParameters& e) {
		std::cerr << e.what() << std::endl;
	} catch (InvalidParameter& e) {
		std::cerr << e.what() << std::endl;
	}
}

static bool findModule(const std::string& modname) {
	for (const auto module : moduleList) {
		if (!modname.compare(module->modName())) {
			currentModule = module;
			return true;
		}
	}

	return false;
}

template<typename T>
void printHelpElement(T name, T desc, const int& width = 20) {
	std::cout << std::left << std::setw(width) << std::setfill(' ') << name;
	std::cout << std::left << std::setw(width) << std::setfill(' ') << desc;
	std::cout << std::endl;
}

static void eval(std::string& command) {
	std::transform(command.begin(), command.end(), command.begin(), tolower);

	/* Exit loop */
	if (command == "\\q" || command == "exit" || command == "quit") {
		interrupted = true;
		return;
	}

	/* Show help */
	if (command == "help" || command == "?") {
		if (!currentModule) {
			std::cout << "Loaded modules:" << std::endl;

			for (const auto module : moduleList) {
				printHelpElement("  " + module->name(), module->description());
			}

			std::cout << std::endl;

			return;
		}

		/* Print functions per module */
		printHelpElement(currentModule->name(), currentModule->description());
		currentModule->commandlist([](const std::string& name, const std::string& desc) {
			printHelpElement("  " + name, desc);
		});

		std::cout << std::endl;

		return;
	}

	/* Move to main */
	if (command == ".." || command == "main") {
		currentModule = nullptr;
		return;
	}

	if (command == "." || command == "module") {
		std::cout << "Current module: ";
		if (currentModule)
			std::cout << currentModule->name();
		else
			std::cout << "(main)";
		std::cout << std::endl;
		return;
	}

	if (findModule(command))
		return;

	try {
		runModuleCommand(command);
	} catch (UnknownCommand& e) {
		std::cerr << e.what() << std::endl;
	}
}

static std::string shellState() {
	if (currentModule)
		return "mavc:" + currentModule->modName() + "> ";

	return "mavc> ";
}

void loadModules() {
	moduleList.push_back(new Cynder());
	moduleList.push_back(new Pitcher());
	moduleList.push_back(new ModChella());
	moduleList.push_back(new ModQuid());
}

void unloadModules() {
	for (const auto module : moduleList) {
		delete module;
	}
}

void runShellLoop() {
	loadModules();

	catch_signals();

	std::cout << "Type 'help' to get started" << std::endl;
	std::cout << shellState();

	std::string input;
	while (std::getline(std::cin, input)) {
		if (input.empty()) {
			std::cout << shellState();
			continue;
		}

		/* Evaluate command */
		eval(input);

		if (interrupted)
			break;

		std::cout << shellState();
	}

	unloadModules();
}

int main(int argc, char *argv[]) {

	cxxopts::Options options(argv[0], "");

	options.add_options("Help")
	("s,hbs", "Verify Host based service config", cxxopts::value<std::string>(), "FILE")
	("h,help", "Print this help");

	try {
		options.parse_positional("positional");
		options.parse(argc, argv);
	} catch (const cxxopts::OptionException& e) {
		std::cerr << "error parsing options: " << e.what() << std::endl;
		return 1;
	}

	if (options.count("help")) {
		std::cerr << options.help({"Help"}) << std::endl;
		return 0;
	}

	if (options.count("hbs")) {
		std::string name = options["hbs"].as<std::string>();
		if (!file_exist(name.c_str())) {
			std::cerr << "error: " << name << ": No such file or directory" << std::endl;
			return 1;
		}

		return ParamUtil::VerifyHbs(name) ? 0 : 1;
	}

	runShellLoop();

	return 0;
}
<commit_msg>Start with loaded module<commit_after>#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <csignal>
#include <iomanip>
#include <exception>

#include "common/util.h"
#include "common/cxxopts.h"
#include "param_util.h"
#include "cynder.h"
#include "pitcher.h"
#include "chella.h"
#include "quid.h"

static bool interrupted = false;
static std::vector<IModule *> moduleList;
static IModule *currentModule = nullptr;

void signal_handler(int signum) {
	interrupted = true;
}

static void catch_signals() {
	struct sigaction action;
	action.sa_handler = signal_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGTERM, &action, NULL);
}

struct UnknownModule : public std::exception {
	const char *what() const throw () {
		return "Unknown module";
	}
};

static void runModuleCommand(const std::string& commandline) {
	std::stringstream ss;
	ss.str(commandline);
	std::string command;
	std::vector<std::string> argv;

	if (!currentModule)
		throw UnknownCommand();

	std::string item;
	while (std::getline(ss, item, ' ')) {
		if (command.empty()) {
			command = item;
			continue;
		}

		argv.push_back(item);
	}

	try {
		currentModule->exec(command, argv);
	} catch (TooFewParameters& e) {
		std::cerr << e.what() << std::endl;
	} catch (InvalidParameter& e) {
		std::cerr << e.what() << std::endl;
	}
}

static bool findModule(const std::string& modname) {
	for (const auto module : moduleList) {
		if (!modname.compare(module->modName())) {
			currentModule = module;
			return true;
		}
	}

	return false;
}

template<typename T>
void printHelpElement(T name, T desc, const int& width = 20) {
	std::cout << std::left << std::setw(width) << std::setfill(' ') << name;
	std::cout << std::left << std::setw(width) << std::setfill(' ') << desc;
	std::cout << std::endl;
}

static void eval(std::string& command) {
	std::transform(command.begin(), command.end(), command.begin(), tolower);

	/* Exit loop */
	if (command == "\\q" || command == "exit" || command == "quit") {
		interrupted = true;
		return;
	}

	/* Show help */
	if (command == "help" || command == "?") {
		if (!currentModule) {
			std::cout << "Loaded modules:" << std::endl;

			for (const auto module : moduleList) {
				printHelpElement("  " + module->name(), module->description());
			}

			std::cout << std::endl;

			return;
		}

		/* Print functions per module */
		printHelpElement(currentModule->name(), currentModule->description());
		currentModule->commandlist([](const std::string& name, const std::string& desc) {
			printHelpElement("  " + name, desc);
		});

		std::cout << std::endl;

		return;
	}

	/* Move to main */
	if (command == ".." || command == "main") {
		currentModule = nullptr;
		return;
	}

	if (command == "." || command == "module") {
		std::cout << "Current module: ";
		if (currentModule)
			std::cout << currentModule->name();
		else
			std::cout << "(main)";
		std::cout << std::endl;
		return;
	}

	if (findModule(command))
		return;

	try {
		runModuleCommand(command);
	} catch (UnknownCommand& e) {
		std::cerr << e.what() << std::endl;
	}
}

static std::string shellState() {
	if (currentModule)
		return "mavc:" + currentModule->modName() + "> ";

	return "mavc> ";
}

void loadModules() {
	moduleList.push_back(new Cynder());
	moduleList.push_back(new Pitcher());
	moduleList.push_back(new ModChella());
	moduleList.push_back(new ModQuid());
}

void unloadModules() {
	for (const auto module : moduleList) {
		delete module;
	}
}

void runShellLoop(const std::string& startmod = "", const std::string& startcmd = "") {
	loadModules();

	catch_signals();

	if (!startmod.empty())
		findModule(startmod);

	// if (!startcmd.empty())

	std::cout << "Type 'help' to get started" << std::endl;
	std::cout << shellState();

	std::string input;
	while (std::getline(std::cin, input)) {
		if (input.empty()) {
			std::cout << shellState();
			continue;
		}

		/* Evaluate command */
		eval(input);

		if (interrupted)
			break;

		std::cout << shellState();
	}

	unloadModules();
}

int main(int argc, char *argv[]) {

	std::string startmod;
	cxxopts::Options options(argv[0], "");

	options.add_options("Help")
	("s,hbs", "Verify Host based service config", cxxopts::value<std::string>(), "FILE")
	("m,module", "Start with module", cxxopts::value<std::string>(), "module")
	("c,command", "Run command", cxxopts::value<std::string>(), "command")
	("h,help", "Print this help");

	try {
		options.parse_positional("positional");
		options.parse(argc, argv);
	} catch (const cxxopts::OptionException& e) {
		std::cerr << "error parsing options: " << e.what() << std::endl;
		return 1;
	}

	if (options.count("help")) {
		std::cerr << options.help({"Help"}) << std::endl;
		return 0;
	}

	if (options.count("module")) {
		startmod = options["module"].as<std::string>();
	}

	if (options.count("hbs")) {
		std::string name = options["hbs"].as<std::string>();
		if (!file_exist(name.c_str())) {
			std::cerr << "error: " << name << ": No such file or directory" << std::endl;
			return 1;
		}

		return ParamUtil::VerifyHbs(name) ? 0 : 1;
	}

	runShellLoop(startmod);

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#pragma once

#include <functional>
#include <memory>
#include <string>
#if defined(_WIN32)
#include <Windows.h>
#define ThreadLocal __declspec(thread)
#else
#include <pthread.h>
#define ThreadLocal __thread
#if defined(__APPLE__)
#include <sys/sysctl.h>
#else
#include <unistd.h>
#endif // #if defined(__APPLE__)
#endif

namespace ouzel
{
    inline uint32_t getCPUCount()
    {
#if defined(_WIN32)
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        return sysinfo.dwNumberOfProcessors;
#else
#if defined(__APPLE__)
        int mib[2];
        mib[0] = CTL_HW;
#ifdef HW_AVAILCPU
        mib[1] = HW_AVAILCPU;
#else
        mib[1] = HW_NCPU;
#endif
        int count;
        size_t size = sizeof(count);
        sysctl(mib, 2, &count, &size, NULL, 0);
        return (count > 0) ? static_cast<uint32_t>(count) : 0;
#elif defined(__linux__) || defined(__ANDROID__)
        int count = sysconf(_SC_NPROCESSORS_ONLN);
        return (count > 0) ? static_cast<uint32_t>(count) : 0;
#else
        return 1;
#endif
#endif
    }

    class Thread final
    {
    public:
        class ID
        {
            friend Thread;
        public:
            bool operator==(const ID& other)
            {
#if defined(_WIN32)
                return threadId == other.threadId;
#else
                return pthread_equal(thread, other.thread) != 0;
#endif
            }

            bool operator!=(const ID& other)
            {
#if defined(_WIN32)
                return threadId != other.threadId;
#else
                return pthread_equal(thread, other.thread) == 0;
#endif
            }

        protected:
#if defined(_WIN32)
            ID(DWORD id):
                threadId(id)
#else
            ID(pthread_t t):
                thread(t)
#endif
            {
            }
        private:
#if defined(_WIN32)
            DWORD threadId = 0;
#else
            pthread_t thread = 0;
#endif
        };

        Thread() {}
        explicit Thread(const std::function<void()>& function, const std::string& name = "");

        ~Thread();

        Thread(const Thread&) = delete;
        Thread& operator=(const Thread&) = delete;

        Thread(Thread&& other);
        Thread& operator=(Thread&& other);

        bool run();
        bool join();

        inline bool isJoinable() const
        {
#if defined(_WIN32)
            return handle != nullptr;
#else
            return thread != 0;
#endif
        }

        ID getId() const
        {
#if defined(_WIN32)
            return threadId;
#else
            return thread;
#endif
        }

        static ID getCurrentThreadId()
        {
#if defined(_WIN32)
            return GetCurrentThreadId();
#else
            return pthread_self();
#endif
        }

        static bool setCurrentThreadName(const std::string& name);

        struct State
        {
            std::function<void()> function;
            std::string name;
        };

    protected:
        std::unique_ptr<State> state;

#if defined(_WIN32)
        HANDLE handle = nullptr;
        DWORD threadId = 0;
#else
        pthread_t thread = 0;
#endif
    };
}
<commit_msg>Implement thread priority setter and getter<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#pragma once

#include <functional>
#include <memory>
#include <string>
#if defined(_WIN32)
#include <Windows.h>
#define ThreadLocal __declspec(thread)
#else
#include <pthread.h>
#define ThreadLocal __thread
#if defined(__APPLE__)
#include <sys/sysctl.h>
#else
#include <unistd.h>
#endif // #if defined(__APPLE__)
#endif

namespace ouzel
{
    inline uint32_t getCPUCount()
    {
#if defined(_WIN32)
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);
        return sysinfo.dwNumberOfProcessors;
#else
#if defined(__APPLE__)
        int mib[2];
        mib[0] = CTL_HW;
#ifdef HW_AVAILCPU
        mib[1] = HW_AVAILCPU;
#else
        mib[1] = HW_NCPU;
#endif
        int count;
        size_t size = sizeof(count);
        sysctl(mib, 2, &count, &size, NULL, 0);
        return (count > 0) ? static_cast<uint32_t>(count) : 0;
#elif defined(__linux__) || defined(__ANDROID__)
        int count = sysconf(_SC_NPROCESSORS_ONLN);
        return (count > 0) ? static_cast<uint32_t>(count) : 0;
#else
        return 1;
#endif
#endif
    }

    class Thread final
    {
    public:
        class ID
        {
            friend Thread;
        public:
            bool operator==(const ID& other)
            {
#if defined(_WIN32)
                return threadId == other.threadId;
#else
                return pthread_equal(thread, other.thread) != 0;
#endif
            }

            bool operator!=(const ID& other)
            {
#if defined(_WIN32)
                return threadId != other.threadId;
#else
                return pthread_equal(thread, other.thread) == 0;
#endif
            }

        protected:
#if defined(_WIN32)
            ID(DWORD id):
                threadId(id)
#else
            ID(pthread_t t):
                thread(t)
#endif
            {
            }
        private:
#if defined(_WIN32)
            DWORD threadId = 0;
#else
            pthread_t thread = 0;
#endif
        };

        Thread() {}
        explicit Thread(const std::function<void()>& function, const std::string& name = "");

        ~Thread();

        Thread(const Thread&) = delete;
        Thread& operator=(const Thread&) = delete;

        Thread(Thread&& other);
        Thread& operator=(Thread&& other);

        bool run();
        bool join();

        int32_t getPriority() const
        {
#if defined(_WIN32)
            return GetThreadPriority(handle);
#else
            int policy;
            sched_param param;
            if (pthread_getschedparam(thread, &policy, &param) == 0) return param.sched_priority;
            return 0;
#endif
        }

        bool setPriority(int32_t priority)
        {
#if defined(_WIN32)
            return SetThreadPriority(handle, priority) != 0;
#else
            sched_param param;
            param.sched_priority = priority;
            return pthread_setschedparam(thread, SCHED_RR, &param) == 0;
#endif
        }

        inline bool isJoinable() const
        {
#if defined(_WIN32)
            return handle != nullptr;
#else
            return thread != 0;
#endif
        }

        ID getId() const
        {
#if defined(_WIN32)
            return threadId;
#else
            return thread;
#endif
        }

        static ID getCurrentThreadId()
        {
#if defined(_WIN32)
            return GetCurrentThreadId();
#else
            return pthread_self();
#endif
        }

        static bool setCurrentThreadName(const std::string& name);

        struct State
        {
            std::function<void()> function;
            std::string name;
        };

    protected:
        std::unique_ptr<State> state;

#if defined(_WIN32)
        HANDLE handle = nullptr;
        DWORD threadId = 0;
#else
        pthread_t thread = 0;
#endif
    };
}
<|endoftext|>


<commit_before>// 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-CHROMIUM file.

#include "browser/url_request_context_getter.h"

#include <algorithm>

#include "browser/net/devtools_network_controller_handle.h"
#include "browser/net/devtools_network_transaction_factory.h"
#include "browser/net_log.h"
#include "browser/network_delegate.h"
#include "common/switches.h"

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/ct_known_logs.h"
#include "net/cert/ct_log_verifier.h"
#include "net/cert/ct_policy_enforcer.h"
#include "net/cert/multi_log_ct_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_server_properties_impl.h"
#include "net/log/net_log.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/url_constants.h"
#include "storage/browser/quota/special_storage_policy.h"

#if defined(USE_NSS_CERTS)
#include "net/cert_net/nss_ocsp.h"
#endif

using content::BrowserThread;

namespace brightray {

std::string URLRequestContextGetter::Delegate::GetUserAgent() {
  return base::EmptyString();
}

std::unique_ptr<net::URLRequestJobFactory>
URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
    content::ProtocolHandlerMap* protocol_handlers) {
  std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory(new net::URLRequestJobFactoryImpl);

  for (auto& it : *protocol_handlers) {
    job_factory->SetProtocolHandler(
        it.first, base::WrapUnique(it.second.release()));
  }
  protocol_handlers->clear();

  job_factory->SetProtocolHandler(
      url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
  job_factory->SetProtocolHandler(
      url::kFileScheme,
      base::WrapUnique(new net::FileProtocolHandler(
          BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
              base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));

  return std::move(job_factory);
}

net::HttpCache::BackendFactory*
URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(const base::FilePath& base_path) {
  base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
  return new net::HttpCache::DefaultBackend(
      net::DISK_CACHE,
      net::CACHE_BACKEND_DEFAULT,
      cache_path,
      0,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
}

std::unique_ptr<net::CertVerifier>
URLRequestContextGetter::Delegate::CreateCertVerifier() {
  return net::CertVerifier::CreateDefault();
}

net::SSLConfigService* URLRequestContextGetter::Delegate::CreateSSLConfigService() {
  return new net::SSLConfigServiceDefaults;
}

std::vector<std::string> URLRequestContextGetter::Delegate::GetCookieableSchemes() {
  return { "http", "https", "ws", "wss" };
}

URLRequestContextGetter::URLRequestContextGetter(
    Delegate* delegate,
    DevToolsNetworkControllerHandle* handle,
    NetLog* net_log,
    const base::FilePath& base_path,
    bool in_memory,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector protocol_interceptors)
    : delegate_(delegate),
      network_controller_handle_(handle),
      net_log_(net_log),
      base_path_(base_path),
      in_memory_(in_memory),
      io_loop_(io_loop),
      file_loop_(file_loop),
      protocol_interceptors_(std::move(protocol_interceptors)),
      job_factory_(nullptr) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (protocol_handlers)
    std::swap(protocol_handlers_, *protocol_handlers);

  if (delegate_)
    user_agent_ = delegate_->GetUserAgent();

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
}

URLRequestContextGetter::~URLRequestContextGetter() {
#if defined(USE_NSS_CERTS)
  net::SetURLRequestContextForNSSHttpIO(NULL);
#endif
}

net::HostResolver* URLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (!url_request_context_.get()) {
    auto& command_line = *base::CommandLine::ForCurrentProcess();
    url_request_context_.reset(new net::URLRequestContext);

#if defined(USE_NSS_CERTS)
    net::SetURLRequestContextForNSSHttpIO(url_request_context_.get());
#endif

    // --log-net-log
    if (net_log_) {
      net_log_->StartLogging(url_request_context_.get());
      url_request_context_->set_net_log(net_log_);
    }

    network_delegate_.reset(delegate_->CreateNetworkDelegate());
    url_request_context_->set_network_delegate(network_delegate_.get());

    storage_.reset(new net::URLRequestContextStorage(url_request_context_.get()));

    std::unique_ptr<net::CookieStore> cookie_store = nullptr;
    auto cookie_path = in_memory_ ?
        base::FilePath() : base_path_.Append(FILE_PATH_LITERAL("Cookies"));
    auto cookie_config = content::CookieStoreConfig(
        cookie_path,
        content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
        nullptr,
        delegate_->CreateCookieDelegate());
    cookie_config.cookieable_schemes = delegate_->GetCookieableSchemes();
    cookie_store = content::CreateCookieStore(cookie_config);
    storage_->set_cookie_store(std::move(cookie_store));
    storage_->set_channel_id_service(base::WrapUnique(
        new net::ChannelIDService(new net::DefaultChannelIDStore(nullptr),
                                  base::WorkerPool::GetTaskRunner(true))));

    std::string accept_lang = l10n_util::GetApplicationLocale("");
    storage_->set_http_user_agent_settings(base::WrapUnique(
        new net::StaticHttpUserAgentSettings(
            net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang),
            user_agent_)));

    std::unique_ptr<net::HostResolver> host_resolver(net::HostResolver::CreateDefaultResolver(nullptr));

    // --host-resolver-rules
    if (command_line.HasSwitch(::switches::kHostResolverRules)) {
      std::unique_ptr<net::MappedHostResolver> remapped_resolver(
          new net::MappedHostResolver(std::move(host_resolver)));
      remapped_resolver->SetRulesFromString(
          command_line.GetSwitchValueASCII(::switches::kHostResolverRules));
      host_resolver = std::move(remapped_resolver);
    }

    // --proxy-server
    net::DhcpProxyScriptFetcherFactory dhcp_factory;
    if (command_line.HasSwitch(switches::kNoProxyServer)) {
      storage_->set_proxy_service(net::ProxyService::CreateDirect());
    } else if (command_line.HasSwitch(switches::kProxyServer)) {
      net::ProxyConfig proxy_config;
      proxy_config.proxy_rules().ParseFromString(
          command_line.GetSwitchValueASCII(switches::kProxyServer));
      proxy_config.proxy_rules().bypass_rules.ParseFromString(
          command_line.GetSwitchValueASCII(switches::kProxyBypassList));
      storage_->set_proxy_service(net::ProxyService::CreateFixed(proxy_config));
    } else if (command_line.HasSwitch(switches::kProxyPacUrl)) {
      auto proxy_config = net::ProxyConfig::CreateFromCustomPacURL(
          GURL(command_line.GetSwitchValueASCII(switches::kProxyPacUrl)));
      proxy_config.set_pac_mandatory(true);
      storage_->set_proxy_service(net::ProxyService::CreateFixed(
          proxy_config));
    } else {
      storage_->set_proxy_service(
          net::CreateProxyServiceUsingV8ProxyResolver(
              std::move(proxy_config_service_),
              new net::ProxyScriptFetcherImpl(url_request_context_.get()),
              dhcp_factory.Create(url_request_context_.get()),
              host_resolver.get(),
              nullptr,
              url_request_context_->network_delegate()));
    }

    std::vector<std::string> schemes;
    schemes.push_back(std::string("basic"));
    schemes.push_back(std::string("digest"));
    schemes.push_back(std::string("ntlm"));
    schemes.push_back(std::string("negotiate"));
#if defined(OS_POSIX)
    http_auth_preferences_.reset(new net::HttpAuthPreferences(schemes,
                                                              std::string()));
#else
    http_auth_preferences_.reset(new net::HttpAuthPreferences(schemes));
#endif

    // --auth-server-whitelist
    if (command_line.HasSwitch(switches::kAuthServerWhitelist)) {
      http_auth_preferences_->set_server_whitelist(
          command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist));
    }

    // --auth-negotiate-delegate-whitelist
    if (command_line.HasSwitch(switches::kAuthNegotiateDelegateWhitelist)) {
      http_auth_preferences_->set_delegate_whitelist(
          command_line.GetSwitchValueASCII(switches::kAuthNegotiateDelegateWhitelist));
    }

    auto auth_handler_factory =
        net::HttpAuthHandlerRegistryFactory::Create(
            http_auth_preferences_.get(), host_resolver.get());

    storage_->set_cert_verifier(delegate_->CreateCertVerifier());
    storage_->set_transport_security_state(
        base::WrapUnique(new net::TransportSecurityState));
    storage_->set_ssl_config_service(delegate_->CreateSSLConfigService());
    storage_->set_http_auth_handler_factory(std::move(auth_handler_factory));
    std::unique_ptr<net::HttpServerProperties> server_properties(
        new net::HttpServerPropertiesImpl);
    storage_->set_http_server_properties(std::move(server_properties));

    std::unique_ptr<net::MultiLogCTVerifier> ct_verifier =
        base::MakeUnique<net::MultiLogCTVerifier>();
    ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
    storage_->set_cert_transparency_verifier(std::move(ct_verifier));
    storage_->set_ct_policy_enforcer(base::MakeUnique<net::CTPolicyEnforcer>());

    net::HttpNetworkSession::Params network_session_params;
    net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
        url_request_context_.get(), &network_session_params);
    network_session_params.ignore_certificate_errors = false;

    // --disable-http2
    if (command_line.HasSwitch(switches::kDisableHttp2)) {
      network_session_params.enable_spdy31 = false;
      network_session_params.enable_http2 = false;
    }

    // --ignore-certificate-errors
    if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
      network_session_params.ignore_certificate_errors = true;

    // --host-rules
    if (command_line.HasSwitch(switches::kHostRules)) {
      host_mapping_rules_.reset(new net::HostMappingRules);
      host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(switches::kHostRules));
      network_session_params.host_mapping_rules = host_mapping_rules_.get();
    }

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(std::move(host_resolver));
    network_session_params.host_resolver = url_request_context_->host_resolver();

    http_network_session_.reset(
        new net::HttpNetworkSession(network_session_params));
    std::unique_ptr<net::HttpCache::BackendFactory> backend;
    if (in_memory_) {
      backend = net::HttpCache::DefaultBackend::InMemory(0);
    } else {
      backend.reset(delegate_->CreateHttpCacheBackendFactory(base_path_));
    }

    if (network_controller_handle_) {
      storage_->set_http_transaction_factory(base::WrapUnique(
          new net::HttpCache(
              base::WrapUnique(new DevToolsNetworkTransactionFactory(
                  network_controller_handle_->GetController(), http_network_session_.get())),
              std::move(backend),
              false)));
    } else {
      storage_->set_http_transaction_factory(base::WrapUnique(
          new net::HttpCache(http_network_session_.get(),
                             std::move(backend),
                             false)));
    }

    std::unique_ptr<net::URLRequestJobFactory> job_factory =
        delegate_->CreateURLRequestJobFactory(&protocol_handlers_);
    job_factory_ = job_factory.get();

    // Set up interceptors in the reverse order.
    std::unique_ptr<net::URLRequestJobFactory> top_job_factory =
        std::move(job_factory);
    content::URLRequestInterceptorScopedVector::reverse_iterator it;
    for (it = protocol_interceptors_.rbegin();
         it != protocol_interceptors_.rend();
         ++it) {
      top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(top_job_factory), base::WrapUnique(*it)));
    }
    protocol_interceptors_.weak_clear();

    storage_->set_job_factory(std::move(top_job_factory));
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}

}  // namespace brightray
<commit_msg>:art:<commit_after>// 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-CHROMIUM file.

#include "browser/url_request_context_getter.h"

#include <algorithm>

#include "browser/net/devtools_network_controller_handle.h"
#include "browser/net/devtools_network_transaction_factory.h"
#include "browser/net_log.h"
#include "browser/network_delegate.h"
#include "common/switches.h"

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/ct_known_logs.h"
#include "net/cert/ct_log_verifier.h"
#include "net/cert/ct_policy_enforcer.h"
#include "net/cert/multi_log_ct_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_server_properties_impl.h"
#include "net/log/net_log.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/url_constants.h"
#include "storage/browser/quota/special_storage_policy.h"

#if defined(USE_NSS_CERTS)
#include "net/cert_net/nss_ocsp.h"
#endif

using content::BrowserThread;

namespace brightray {

std::string URLRequestContextGetter::Delegate::GetUserAgent() {
  return base::EmptyString();
}

std::unique_ptr<net::URLRequestJobFactory>
URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
    content::ProtocolHandlerMap* protocol_handlers) {
  std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory(new net::URLRequestJobFactoryImpl);

  for (auto& it : *protocol_handlers) {
    job_factory->SetProtocolHandler(
        it.first, base::WrapUnique(it.second.release()));
  }
  protocol_handlers->clear();

  job_factory->SetProtocolHandler(
      url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler));
  job_factory->SetProtocolHandler(
      url::kFileScheme,
      base::WrapUnique(new net::FileProtocolHandler(
          BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
              base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));

  return std::move(job_factory);
}

net::HttpCache::BackendFactory*
URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(const base::FilePath& base_path) {
  base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
  return new net::HttpCache::DefaultBackend(
      net::DISK_CACHE,
      net::CACHE_BACKEND_DEFAULT,
      cache_path,
      0,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
}

std::unique_ptr<net::CertVerifier>
URLRequestContextGetter::Delegate::CreateCertVerifier() {
  return net::CertVerifier::CreateDefault();
}

net::SSLConfigService* URLRequestContextGetter::Delegate::CreateSSLConfigService() {
  return new net::SSLConfigServiceDefaults;
}

std::vector<std::string> URLRequestContextGetter::Delegate::GetCookieableSchemes() {
  return { "http", "https", "ws", "wss" };
}

URLRequestContextGetter::URLRequestContextGetter(
    Delegate* delegate,
    DevToolsNetworkControllerHandle* handle,
    NetLog* net_log,
    const base::FilePath& base_path,
    bool in_memory,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector protocol_interceptors)
    : delegate_(delegate),
      network_controller_handle_(handle),
      net_log_(net_log),
      base_path_(base_path),
      in_memory_(in_memory),
      io_loop_(io_loop),
      file_loop_(file_loop),
      protocol_interceptors_(std::move(protocol_interceptors)),
      job_factory_(nullptr) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (protocol_handlers)
    std::swap(protocol_handlers_, *protocol_handlers);

  if (delegate_)
    user_agent_ = delegate_->GetUserAgent();

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
}

URLRequestContextGetter::~URLRequestContextGetter() {
#if defined(USE_NSS_CERTS)
  net::SetURLRequestContextForNSSHttpIO(NULL);
#endif
}

net::HostResolver* URLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (!url_request_context_.get()) {
    auto& command_line = *base::CommandLine::ForCurrentProcess();
    url_request_context_.reset(new net::URLRequestContext);

#if defined(USE_NSS_CERTS)
    net::SetURLRequestContextForNSSHttpIO(url_request_context_.get());
#endif

    // --log-net-log
    if (net_log_) {
      net_log_->StartLogging(url_request_context_.get());
      url_request_context_->set_net_log(net_log_);
    }

    network_delegate_.reset(delegate_->CreateNetworkDelegate());
    url_request_context_->set_network_delegate(network_delegate_.get());

    storage_.reset(new net::URLRequestContextStorage(url_request_context_.get()));

    auto cookie_path = in_memory_ ?
        base::FilePath() : base_path_.Append(FILE_PATH_LITERAL("Cookies"));
    auto cookie_config = content::CookieStoreConfig(
        cookie_path,
        content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
        nullptr,
        delegate_->CreateCookieDelegate());
    cookie_config.cookieable_schemes = delegate_->GetCookieableSchemes();
    std::unique_ptr<net::CookieStore> cookie_store =
        content::CreateCookieStore(cookie_config);
    storage_->set_cookie_store(std::move(cookie_store));
    storage_->set_channel_id_service(base::WrapUnique(
        new net::ChannelIDService(new net::DefaultChannelIDStore(nullptr),
                                  base::WorkerPool::GetTaskRunner(true))));

    std::string accept_lang = l10n_util::GetApplicationLocale("");
    storage_->set_http_user_agent_settings(base::WrapUnique(
        new net::StaticHttpUserAgentSettings(
            net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang),
            user_agent_)));

    std::unique_ptr<net::HostResolver> host_resolver(net::HostResolver::CreateDefaultResolver(nullptr));

    // --host-resolver-rules
    if (command_line.HasSwitch(::switches::kHostResolverRules)) {
      std::unique_ptr<net::MappedHostResolver> remapped_resolver(
          new net::MappedHostResolver(std::move(host_resolver)));
      remapped_resolver->SetRulesFromString(
          command_line.GetSwitchValueASCII(::switches::kHostResolverRules));
      host_resolver = std::move(remapped_resolver);
    }

    // --proxy-server
    net::DhcpProxyScriptFetcherFactory dhcp_factory;
    if (command_line.HasSwitch(switches::kNoProxyServer)) {
      storage_->set_proxy_service(net::ProxyService::CreateDirect());
    } else if (command_line.HasSwitch(switches::kProxyServer)) {
      net::ProxyConfig proxy_config;
      proxy_config.proxy_rules().ParseFromString(
          command_line.GetSwitchValueASCII(switches::kProxyServer));
      proxy_config.proxy_rules().bypass_rules.ParseFromString(
          command_line.GetSwitchValueASCII(switches::kProxyBypassList));
      storage_->set_proxy_service(net::ProxyService::CreateFixed(proxy_config));
    } else if (command_line.HasSwitch(switches::kProxyPacUrl)) {
      auto proxy_config = net::ProxyConfig::CreateFromCustomPacURL(
          GURL(command_line.GetSwitchValueASCII(switches::kProxyPacUrl)));
      proxy_config.set_pac_mandatory(true);
      storage_->set_proxy_service(net::ProxyService::CreateFixed(
          proxy_config));
    } else {
      storage_->set_proxy_service(
          net::CreateProxyServiceUsingV8ProxyResolver(
              std::move(proxy_config_service_),
              new net::ProxyScriptFetcherImpl(url_request_context_.get()),
              dhcp_factory.Create(url_request_context_.get()),
              host_resolver.get(),
              nullptr,
              url_request_context_->network_delegate()));
    }

    std::vector<std::string> schemes;
    schemes.push_back(std::string("basic"));
    schemes.push_back(std::string("digest"));
    schemes.push_back(std::string("ntlm"));
    schemes.push_back(std::string("negotiate"));
#if defined(OS_POSIX)
    http_auth_preferences_.reset(new net::HttpAuthPreferences(schemes,
                                                              std::string()));
#else
    http_auth_preferences_.reset(new net::HttpAuthPreferences(schemes));
#endif

    // --auth-server-whitelist
    if (command_line.HasSwitch(switches::kAuthServerWhitelist)) {
      http_auth_preferences_->set_server_whitelist(
          command_line.GetSwitchValueASCII(switches::kAuthServerWhitelist));
    }

    // --auth-negotiate-delegate-whitelist
    if (command_line.HasSwitch(switches::kAuthNegotiateDelegateWhitelist)) {
      http_auth_preferences_->set_delegate_whitelist(
          command_line.GetSwitchValueASCII(switches::kAuthNegotiateDelegateWhitelist));
    }

    auto auth_handler_factory =
        net::HttpAuthHandlerRegistryFactory::Create(
            http_auth_preferences_.get(), host_resolver.get());

    storage_->set_cert_verifier(delegate_->CreateCertVerifier());
    storage_->set_transport_security_state(
        base::WrapUnique(new net::TransportSecurityState));
    storage_->set_ssl_config_service(delegate_->CreateSSLConfigService());
    storage_->set_http_auth_handler_factory(std::move(auth_handler_factory));
    std::unique_ptr<net::HttpServerProperties> server_properties(
        new net::HttpServerPropertiesImpl);
    storage_->set_http_server_properties(std::move(server_properties));

    std::unique_ptr<net::MultiLogCTVerifier> ct_verifier =
        base::MakeUnique<net::MultiLogCTVerifier>();
    ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
    storage_->set_cert_transparency_verifier(std::move(ct_verifier));
    storage_->set_ct_policy_enforcer(base::MakeUnique<net::CTPolicyEnforcer>());

    net::HttpNetworkSession::Params network_session_params;
    net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
        url_request_context_.get(), &network_session_params);
    network_session_params.ignore_certificate_errors = false;

    // --disable-http2
    if (command_line.HasSwitch(switches::kDisableHttp2)) {
      network_session_params.enable_spdy31 = false;
      network_session_params.enable_http2 = false;
    }

    // --ignore-certificate-errors
    if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
      network_session_params.ignore_certificate_errors = true;

    // --host-rules
    if (command_line.HasSwitch(switches::kHostRules)) {
      host_mapping_rules_.reset(new net::HostMappingRules);
      host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(switches::kHostRules));
      network_session_params.host_mapping_rules = host_mapping_rules_.get();
    }

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(std::move(host_resolver));
    network_session_params.host_resolver = url_request_context_->host_resolver();

    http_network_session_.reset(
        new net::HttpNetworkSession(network_session_params));
    std::unique_ptr<net::HttpCache::BackendFactory> backend;
    if (in_memory_) {
      backend = net::HttpCache::DefaultBackend::InMemory(0);
    } else {
      backend.reset(delegate_->CreateHttpCacheBackendFactory(base_path_));
    }

    if (network_controller_handle_) {
      storage_->set_http_transaction_factory(base::WrapUnique(
          new net::HttpCache(
              base::WrapUnique(new DevToolsNetworkTransactionFactory(
                  network_controller_handle_->GetController(), http_network_session_.get())),
              std::move(backend),
              false)));
    } else {
      storage_->set_http_transaction_factory(base::WrapUnique(
          new net::HttpCache(http_network_session_.get(),
                             std::move(backend),
                             false)));
    }

    std::unique_ptr<net::URLRequestJobFactory> job_factory =
        delegate_->CreateURLRequestJobFactory(&protocol_handlers_);
    job_factory_ = job_factory.get();

    // Set up interceptors in the reverse order.
    std::unique_ptr<net::URLRequestJobFactory> top_job_factory =
        std::move(job_factory);
    content::URLRequestInterceptorScopedVector::reverse_iterator it;
    for (it = protocol_interceptors_.rbegin();
         it != protocol_interceptors_.rend();
         ++it) {
      top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(top_job_factory), base::WrapUnique(*it)));
    }
    protocol_interceptors_.weak_clear();

    storage_->set_job_factory(std::move(top_job_factory));
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}

}  // namespace brightray
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <scapig2@yandex.ru>
** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "serialportinfo.h"
#include "serialportinfo_p.h"
#include "ttylocker_unix_p.h"
#include "serialportengine_unix_p.h"

#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#if defined (Q_OS_LINUX)
#  include <linux/serial.h>
#endif

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)
extern "C"
{
#  include <libudev.h>
}
#else
#  include <QtCore/qdir.h>
#endif

#include <QtCore/qstringlist.h>
#include <QtCore/qregexp.h>
#include <QtCore/qfile.h>

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

// For detail enumerate - skipping, filters is not used.
// Instead of filters used libudev.

#else

// For simple enumerate.

static QStringList generateFiltersOfDevices()
{
    QStringList l;

#  if defined (Q_OS_LINUX)
    l << QLatin1String("ttyS*")    // Standart UART 8250 and etc.
      << QLatin1String("ttyUSB*")  // Usb/serial converters PL2303 and etc.
      << QLatin1String("ttyACM*")  // CDC_ACM converters (i.e. Mobile Phones).
      << QLatin1String("ttyGS*")   // Gadget serial device (i.e. Mobile Phones with gadget serial driver).
      << QLatin1String("ttyMI*")   // MOXA pci/serial converters.
      << QLatin1String("rfcomm*"); // Bluetooth serial device.
#  elif defined (Q_OS_FREEBSD)
    l << QLatin1String("cu*");
#  else
    // Here for other *nix OS.
#  endif

    return l;
}

// Only for a simple enumeration by the mask of all available
// devices in /dev directory. Used in the following cases:
// - for Gnu/Linux without libudev
// - for any other *nix, bsd (exception Mac OSX)
inline QStringList& filtersOfDevices()
{
    static QStringList l = generateFiltersOfDevices();
    return l;
}

#endif

QT_BEGIN_NAMESPACE_SERIALPORT

/* Public methods */

QList<SerialPortInfo> SerialPortInfo::availablePorts()
{
    QList<SerialPortInfo> ports;

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

    // Detailed enumerate devices for Gnu/Linux with use libudev.

    struct ::udev *udev = ::udev_new();
    if (udev) {

        struct ::udev_enumerate *enumerate =
                ::udev_enumerate_new(udev);

        if (enumerate) {

            ::udev_enumerate_add_match_subsystem(enumerate, "tty");
            ::udev_enumerate_scan_devices(enumerate);

            struct ::udev_list_entry *devices =
                    ::udev_enumerate_get_list_entry(enumerate);

            struct ::udev_list_entry *dev_list_entry;
            udev_list_entry_foreach(dev_list_entry, devices) {

                struct ::udev_device *dev =
                        ::udev_device_new_from_syspath(udev,
                                                       ::udev_list_entry_get_name(dev_list_entry));

                if (dev) {

                    SerialPortInfo info;

                    info.d_ptr->device =
                            QString::fromLatin1(::udev_device_get_devnode(dev));
                    info.d_ptr->portName =
                            QString::fromLatin1(::udev_device_get_sysname(dev));

                    struct ::udev_device *parentdev = ::udev_device_get_parent(dev);

                    if (parentdev) {

                        QString subsys(QLatin1String(::udev_device_get_subsystem(parentdev)));

                        bool do_append = true;

                        if (subsys.contains(QLatin1String("usb"))) {
                            info.d_ptr->description =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL_FROM_DATABASE"));
                            info.d_ptr->manufacturer =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR_FROM_DATABASE"));
                            info.d_ptr->vendorIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR_ID"));
                            info.d_ptr->productIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL_ID"));

                        } else if (subsys.contains(QLatin1String("pnp"))) {
                            // FIXME: How can I get a additional info about standard serial devices?

                        } else {
                            // Others subsystems.
                            // Skip, while don't use.
                            do_append = false;
                        }

                        if (do_append)
                            ports.append(info);
                    }

                    ::udev_device_unref(dev);
                }

            }

            ::udev_enumerate_unref(enumerate);
        }

        ::udev_unref(udev);
    }

#elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB)

    // TODO: Implement me.
    //

#else

    // Simple enumerate devices for other *nix OS in device directory /dev.

    QDir devDir(QLatin1String("/dev"));
    if (devDir.exists()) {

        devDir.setNameFilters(filtersOfDevices());
        devDir.setFilter(QDir::Files | QDir::System);

        QStringList foundDevices; // Found devices list.

        foreach (const QFileInfo &fi, devDir.entryInfoList()) {
            if (!fi.isDir()) {

                QString s = fi.absoluteFilePath().split('.').at(0);
                if (!foundDevices.contains(s)) {
                    foundDevices.append(s);

                    SerialPortInfo info;

                    info.d_ptr->device = s;
                    info.d_ptr->portName = s.remove(QRegExp(QLatin1String("/[\\w|\\d|\\s]+/")));

                    // Get description, manufacturer, vendor identifier, product
                    // identifier are not supported.

                    ports.append(info);

                }
            }
        }
    }

#endif

    return ports;
}

QList<qint32> SerialPortInfo::standardRates()
{
    return UnixSerialPortEngine::standardRates();
}

bool SerialPortInfo::isBusy() const
{
    bool currentPid = false;
    return TtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid);
}

bool SerialPortInfo::isValid() const
{
    QFile f(systemLocation());
    return f.exists();
}

QT_END_NAMESPACE_SERIALPORT
<commit_msg>Add support for the gadget serial driver while using udev<commit_after>/****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <scapig2@yandex.ru>
** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "serialportinfo.h"
#include "serialportinfo_p.h"
#include "ttylocker_unix_p.h"
#include "serialportengine_unix_p.h"

#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#if defined (Q_OS_LINUX)
#  include <linux/serial.h>
#endif

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)
extern "C"
{
#  include <libudev.h>
}
#else
#  include <QtCore/qdir.h>
#endif

#include <QtCore/qstringlist.h>
#include <QtCore/qregexp.h>
#include <QtCore/qfile.h>

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

// For detail enumerate - skipping, filters is not used.
// Instead of filters used libudev.

#else

// For simple enumerate.

static QStringList generateFiltersOfDevices()
{
    QStringList l;

#  if defined (Q_OS_LINUX)
    l << QLatin1String("ttyS*")    // Standart UART 8250 and etc.
      << QLatin1String("ttyUSB*")  // Usb/serial converters PL2303 and etc.
      << QLatin1String("ttyACM*")  // CDC_ACM converters (i.e. Mobile Phones).
      << QLatin1String("ttyGS*")   // Gadget serial device (i.e. Mobile Phones with gadget serial driver).
      << QLatin1String("ttyMI*")   // MOXA pci/serial converters.
      << QLatin1String("rfcomm*"); // Bluetooth serial device.
#  elif defined (Q_OS_FREEBSD)
    l << QLatin1String("cu*");
#  else
    // Here for other *nix OS.
#  endif

    return l;
}

// Only for a simple enumeration by the mask of all available
// devices in /dev directory. Used in the following cases:
// - for Gnu/Linux without libudev
// - for any other *nix, bsd (exception Mac OSX)
inline QStringList& filtersOfDevices()
{
    static QStringList l = generateFiltersOfDevices();
    return l;
}

#endif

QT_BEGIN_NAMESPACE_SERIALPORT

/* Public methods */

QList<SerialPortInfo> SerialPortInfo::availablePorts()
{
    QList<SerialPortInfo> ports;

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

    // Detailed enumerate devices for Gnu/Linux with use libudev.

    struct ::udev *udev = ::udev_new();
    if (udev) {

        struct ::udev_enumerate *enumerate =
                ::udev_enumerate_new(udev);

        if (enumerate) {

            ::udev_enumerate_add_match_subsystem(enumerate, "tty");
            ::udev_enumerate_scan_devices(enumerate);

            struct ::udev_list_entry *devices =
                    ::udev_enumerate_get_list_entry(enumerate);

            struct ::udev_list_entry *dev_list_entry;
            udev_list_entry_foreach(dev_list_entry, devices) {

                struct ::udev_device *dev =
                        ::udev_device_new_from_syspath(udev,
                                                       ::udev_list_entry_get_name(dev_list_entry));

                if (dev) {

                    SerialPortInfo info;

                    info.d_ptr->device =
                            QString::fromLatin1(::udev_device_get_devnode(dev));
                    info.d_ptr->portName =
                            QString::fromLatin1(::udev_device_get_sysname(dev));

                    struct ::udev_device *parentdev = ::udev_device_get_parent(dev);

                    if (parentdev) {

                        QString subsys(QLatin1String(::udev_device_get_subsystem(parentdev)));

                        bool do_append = true;

                        if (subsys.contains(QLatin1String("usb"))) {
                            info.d_ptr->description =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL_FROM_DATABASE"));
                            info.d_ptr->manufacturer =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR_FROM_DATABASE"));
                            info.d_ptr->vendorIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR_ID"));
                            info.d_ptr->productIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL_ID"));

                        } else if (subsys.contains(QLatin1String("pnp"))) {
                            // FIXME: How can I get a additional info about standard serial devices?

                        } else if (subsys.isEmpty()) {
                            // FIXME: How to get additional information about serial devices with empty subsystem, like gadget serial devices ?
                        } else if (subsys == QLatin1String("platform")) {
                            // Platform subsystems.
                            // Skip, while don't use.
                            do_append = false;
                        }

                        if (do_append)
                            ports.append(info);
                    }

                    ::udev_device_unref(dev);
                }

            }

            ::udev_enumerate_unref(enumerate);
        }

        ::udev_unref(udev);
    }

#elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB)

    // TODO: Implement me.
    //

#else

    // Simple enumerate devices for other *nix OS in device directory /dev.

    QDir devDir(QLatin1String("/dev"));
    if (devDir.exists()) {

        devDir.setNameFilters(filtersOfDevices());
        devDir.setFilter(QDir::Files | QDir::System);

        QStringList foundDevices; // Found devices list.

        foreach (const QFileInfo &fi, devDir.entryInfoList()) {
            if (!fi.isDir()) {

                QString s = fi.absoluteFilePath().split('.').at(0);
                if (!foundDevices.contains(s)) {
                    foundDevices.append(s);

                    SerialPortInfo info;

                    info.d_ptr->device = s;
                    info.d_ptr->portName = s.remove(QRegExp(QLatin1String("/[\\w|\\d|\\s]+/")));

                    // Get description, manufacturer, vendor identifier, product
                    // identifier are not supported.

                    ports.append(info);

                }
            }
        }
    }

#endif

    return ports;
}

QList<qint32> SerialPortInfo::standardRates()
{
    return UnixSerialPortEngine::standardRates();
}

bool SerialPortInfo::isBusy() const
{
    bool currentPid = false;
    return TtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid);
}

bool SerialPortInfo::isValid() const
{
    QFile f(systemLocation());
    return f.exists();
}

QT_END_NAMESPACE_SERIALPORT
<|endoftext|>


<commit_before>// RUN: %clang -target i386-pc-win32 -fms-extensions -fsyntax-only %s

// Get size_t, but avoid including mm_malloc.h which includes stdlib.h which may
// not exist.
#include <stdint.h>
#undef __STDC_HOSTED__

#include <Intrin.h>

template <typename T>
void foo(T V) {}
<commit_msg>Use -ffreestanding in ms-intrin.cpp and define size_t manually.<commit_after>// RUN: %clang -target i386-pc-win32 -fms-extensions -ffreestanding -fsyntax-only %s

// Intrin.h needs size_t, but -ffreestanding prevents us from getting it from
// stddef.h.  Work around it with this typedef.
typedef __SIZE_TYPE__ size_t;

#include <Intrin.h>

// Use some C++ to make sure we closed the extern "C" brackets.
template <typename T>
void foo(T V) {}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -Xclang -verify | FileCheck %s

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <cmath>

cling::Value V;
V // CHECK: (cling::Value &) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::Value &) boxes [(int) 1]

gCling->evaluate("(void)V", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]

// Returns must put the result in the Value.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(const char [5]) "true"]
gCling->evaluate("if (cond) return; else return 12;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]
gCling->evaluate("if (cond) return; int aa = 12;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(int) 0]

gCling->evaluate("bool a = [](){return true;};", V);
V // CHECK-NEXT: (cling::Value &) boxes [(bool) true]

gCling->evaluate("auto a = 12.3; a;", V);
V // CHECK: (cling::Value &) boxes [(double) 12.300000]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::Value &) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::Value &) boxes [(int *) 0x12 <invalid memory address>]

cling::Value Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::Value; they are returned by reference.
Result // CHECK: (cling::Value &) boxes [(cling::Value &) boxes [(int *) 0x12 <invalid memory address>]]
V // CHECK: (cling::Value &) boxes [(int *) 0x12 <invalid memory address>]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::Value &) boxes [(double) 1.000000]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::Value &) boxes [(double) 1.000000]
one // CHECK: (double) 1
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Multi-dim arrays (ROOT-7016)
gCling->evaluate("int multiDimArray[2][3][4]{{{1,2,3,4},{11,12,13,14},{21,22,23,24}},"
                 "{{101,102,103,104},{111,112,113,114},{121,122,123,124}}};", V);
V // CHECK-NEXT: (cling::Value &) boxes [(int [2][3][4]) { { { 1, 2, 3, 4 }, { 11, 12, 13, 14 }, { 21, 22, 23, 24 } }, { { 101, 102, 103, 104 }, { 111, 112, 113, 114 }, { 121, 122, 123, 124 } } }]

// Check lifetime of objects in Value
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::Value* VOnHeap = new cling::Value();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::Value &) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::Value();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::Value &) boxes [(std::vector<WithDtor>) {{{ (@0x.*, )*@0x.* }}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// long doubles (tricky for the JIT).
gCling->evaluate("17.42L", V);
V // CHECK: (cling::Value &) boxes [(long double) 17.42{{[0-9]*}}L]

// Test references, temporaries
.rawInput 1
extern "C" int printf(const char*,...);
struct Tracer {
  std::string Content;
  static int InstanceCount;
  Tracer(const char* str): Content(str) { ++InstanceCount; dump("ctor"); }
  Tracer(const Tracer& o): Content(o.Content + "+") {
    ++InstanceCount; dump("copy");
  }
  ~Tracer() {--InstanceCount; dump("dtor");}
  std::string asStr() const {
    return Content + "{" + (char)('0' + InstanceCount) + "}";
  }
  void dump(const char* tag) { printf("%s:%s\n", asStr().c_str(), tag); }
};
int Tracer::InstanceCount = 0;

Tracer ObjMaker() { return Tracer("MADE"); }
Tracer& RefMaker() { static Tracer R("REF"); return R; }
const Tracer& ConstRefMaker() {static Tracer R("CONSTREF"); return R;}
namespace cling {
  // FIXME: inline printValue is not used by PrintClingValue()!
  std::string printValue(const Tracer* const p, const Tracer* const u,
                         const Value& V) {
    return p->asStr();
  }
}
void dumpTracerSVR(cling::Value& svr) {
  ((Tracer*)svr.getAs<void*>())->dump("dump");
}
.rawInput 0

// Creating the static in constructs one object. It gets returned by
// reference; it should only be destructed by ~JIT, definitely not by
// ~Value (which should only store a Tracer&)
gCling->evaluate("RefMaker()", V);
// This is the local static:
// CHECK: REF{1}:ctor
printf("RefMaker() done\n"); // CHECK-NEXT: RefMaker() done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer &) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: REF{1}:dump

// Setting a new value should destruct the old - BUT it's a ref thus no
// destruction.

// Create a temporary. Copies it into V through placement-new and copy
// construction. The latter is elided; the temporary *is* what's stored in V.
// Thus all we see is the construction of the temporary.
gCling->evaluate("ObjMaker()", V);
// The temporary gets created:
// CHECK-NEXT:MADE{2}:ctor
printf("ObjMaker() done\n"); //CHECK-NEXT: ObjMaker() done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: MADE{2}:dump

// Creating a variable:
Tracer RT("VAR"); // CHECK-NEXT: VAR{3}:ctor

// The following is a declRefExpr of lvalue type. We explicitly treat this as
// a reference; i.e. the cling::Value will claim to store a Tracer&. No extra
// construction, no extra allocation should happen.
//
// Setting a new value should destruct the old:
// CHECK-NEXT: MADE{2}:dtor
gCling->evaluate("RT", V); // should not call any ctor!
printf("RT done\n"); //CHECK-NEXT: RT done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer &) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: VAR{2}:dump

// The following creates a copy, explicitly. This temporary object is then put
// into the Value.
//
gCling->evaluate("(Tracer)RT", V);
// Copies RT:
//CHECK-NEXT: VAR+{3}:copy
printf("(Tracer)RT done\n"); //CHECK-NEXT: RT done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: VAR+{3}:dump

// Check eval of array var
Tracer arrV[] = {ObjMaker(), ObjMaker(), ObjMaker()};
// The array is built:
//CHECK-NEXT: MADE{4}:ctor
//CHECK-NEXT: MADE{5}:ctor
//CHECK-NEXT: MADE{6}:ctor

gCling->evaluate("arrV", V);
// Now V gets destructed...
//CHECK-NEXT: VAR+{5}:dtor
// ...and the elements are copied:
//CHECK-NEXT: MADE+{6}:copy
//CHECK-NEXT: MADE+{7}:copy
//CHECK-NEXT: MADE+{8}:copy

V // CHECK-NEXT: (cling::Value &) boxes [(Tracer [3]) { @{{.*}}, @{{.*}}, @{{.*}} }]

// Destruct the variables with static storage:
// Destruct arrV:
//CHECK-NEXT: MADE{7}:dtor
//CHECK-NEXT: MADE{6}:dtor
//CHECK-NEXT: MADE{5}:dtor

// CHECK-NEXT: VAR{4}:dtor
// CHECK-NEXT: REF{3}:dtor

//CHECK-NEXT: MADE+{2}:dtor
//CHECK-NEXT: MADE+{1}:dtor
//CHECK-NEXT: MADE+{0}:dtor
<commit_msg>Change evaluation test to track instances better.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -Xclang -verify | FileCheck %s

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <cmath>

cling::Value V;
V // CHECK: (cling::Value &) <<<invalid>>> @0x{{.*}}

gCling->evaluate("return 1;", V);
V // CHECK: (cling::Value &) boxes [(int) 1]

gCling->evaluate("(void)V", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]

// Returns must put the result in the Value.
bool cond = true;
gCling->evaluate("if (cond) return \"true\"; else return 0;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(const char [5]) "true"]
gCling->evaluate("if (cond) return; else return 12;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]
gCling->evaluate("if (cond) return; int aa = 12;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(void) ]
gCling->evaluate("cond = false; if (cond) return \"true\"; else return 0;", V);
V // CHECK-NEXT: (cling::Value &) boxes [(int) 0]

gCling->evaluate("bool a = [](){return true;};", V);
V // CHECK-NEXT: (cling::Value &) boxes [(bool) true]

gCling->evaluate("auto a = 12.3; a;", V);
V // CHECK: (cling::Value &) boxes [(double) 12.300000]

long LongV = 17;
gCling->evaluate("LongV;", V);
V // CHECK: (cling::Value &) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", V);
V // CHECK: (cling::Value &) boxes [(int *) 0x12 <invalid memory address>]

cling::Value Result;
gCling->evaluate("V", Result);
// Here we check what happens for record type like cling::Value; they are returned by reference.
Result // CHECK: (cling::Value &) boxes [(cling::Value &) boxes [(int *) 0x12 <invalid memory address>]]
V // CHECK: (cling::Value &) boxes [(int *) 0x12 <invalid memory address>]

// Savannah #96277
gCling->evaluate("gCling->declare(\"double sin(double);\"); double one = sin(3.141/2);", V);
V // CHECK: (cling::Value &) boxes [(double) 1.000000]

gCling->process("double one = sin(3.141/2);", &V);
V // CHECK: (cling::Value &) boxes [(double) 1.000000]
one // CHECK: (double) 1
int one; // expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}

// Make sure that PR#98434 doesn't get reintroduced.
.rawInput
void f(int) { return; }
.rawInput

gCling->evaluate("f", V);
V.isValid() //CHECK: {{\([_]B|b}}ool) true
// end PR#98434

// Multi-dim arrays (ROOT-7016)
gCling->evaluate("int multiDimArray[2][3][4]{{{1,2,3,4},{11,12,13,14},{21,22,23,24}},"
                 "{{101,102,103,104},{111,112,113,114},{121,122,123,124}}};", V);
V // CHECK-NEXT: (cling::Value &) boxes [(int [2][3][4]) { { { 1, 2, 3, 4 }, { 11, 12, 13, 14 }, { 21, 22, 23, 24 } }, { { 101, 102, 103, 104 }, { 111, 112, 113, 114 }, { 121, 122, 123, 124 } } }]

// Check lifetime of objects in Value
.rawInput 1
struct WithDtor {
   static int fgCount;
   WithDtor() { ++fgCount; }
   WithDtor(const WithDtor&) { ++fgCount; }
   ~WithDtor() { --fgCount; }
};
int WithDtor::fgCount = 0;
WithDtor getWithDtor() { return WithDtor(); }
#include <vector>
std::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }
.rawInput 0

cling::Value* VOnHeap = new cling::Value();
gCling->evaluate("getWithDtor()", *VOnHeap);
*VOnHeap //CHECK: (cling::Value &) boxes [(WithDtor) @0x{{.*}}]
WithDtor::fgCount //CHECK: (int) 1
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// Check destructor call for templates
VOnHeap = new cling::Value();
gCling->evaluate("getWithDtorVec()", *VOnHeap);
*VOnHeap //CHECK: (cling::Value &) boxes [(std::vector<WithDtor>) {{{ (@0x.*, )*@0x.* }}}]
WithDtor::fgCount //CHECK: (int) 7
delete VOnHeap;
WithDtor::fgCount //CHECK: (int) 0

// long doubles (tricky for the JIT).
gCling->evaluate("17.42L", V);
V // CHECK: (cling::Value &) boxes [(long double) 17.42{{[0-9]*}}L]

// Test references, temporaries
.rawInput 1
extern "C" int printf(const char*,...);
struct Tracer {
  std::string Content;
  int Instance;
  static int InstanceCount;
  Tracer(const char* str): Content(str), Instance(++InstanceCount) {
    dump("ctor");
  }
  Tracer(const Tracer& o): Content(o.Content + "+"), Instance(++InstanceCount) {
    dump("copy");
  }
  ~Tracer() { dump("dtor");}
  std::string asStr() const {
    return Content + "{" + std::to_string(Instance) + "}";
  }
  void dump(const char* tag) { printf("%s:%s\n", asStr().c_str(), tag); }
};
int Tracer::InstanceCount = 0;

Tracer ObjMaker() { return Tracer("MADE"); }
Tracer& RefMaker() { static Tracer R("REF"); return R; }
const Tracer& ConstRefMaker() {static Tracer R("CONSTREF"); return R;}
namespace cling {
  // FIXME: inline printValue is not used by PrintClingValue()!
  std::string printValue(const Tracer* const p, const Tracer* const u,
                         const Value& V) {
    return p->asStr();
  }
}
void dumpTracerSVR(cling::Value& svr) {
  ((Tracer*)svr.getAs<void*>())->dump("dump");
}
.rawInput 0

// Creating the static in constructs one object. It gets returned by
// reference; it should only be destructed by ~JIT, definitely not by
// ~Value (which should only store a Tracer&)
gCling->evaluate("RefMaker()", V);
// This is the local static:
// CHECK: REF{1}:ctor
printf("RefMaker() done\n"); // CHECK-NEXT: RefMaker() done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer &) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: REF{1}:dump

// Setting a new value should destruct the old - BUT it's a ref thus no
// destruction.

// Create a temporary. Copies it into V through placement-new and copy
// construction. The latter is elided; the temporary *is* what's stored in V.
// Thus all we see is the construction of the temporary.
gCling->evaluate("ObjMaker()", V);
// The temporary gets created:
// CHECK-NEXT:MADE{2}:ctor
printf("ObjMaker() done\n"); //CHECK-NEXT: ObjMaker() done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: MADE{2}:dump

// Creating a variable:
Tracer RT("VAR"); // CHECK-NEXT: VAR{3}:ctor

// The following is a declRefExpr of lvalue type. We explicitly treat this as
// a reference; i.e. the cling::Value will claim to store a Tracer&. No extra
// construction, no extra allocation should happen.
//
// Setting a new value should destruct the old:
// CHECK-NEXT: MADE{2}:dtor
gCling->evaluate("RT", V); // should not call any ctor!
printf("RT done\n"); //CHECK-NEXT: RT done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer &) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: VAR{3}:dump

// The following creates a copy, explicitly. This temporary object is then put
// into the Value.
//
gCling->evaluate("(Tracer)RT", V);
// Copies RT:
//CHECK-NEXT: VAR+{4}:copy
printf("(Tracer)RT done\n"); //CHECK-NEXT: RT done
V // CHECK-NEXT: (cling::Value &) boxes [(Tracer) @{{.*}}]
dumpTracerSVR(V); // CHECK-NEXT: VAR+{4}:dump

// Check eval of array var
Tracer arrV[] = {ObjMaker(), ObjMaker(), ObjMaker()};
// The array is built:
//CHECK-NEXT: MADE{5}:ctor
//CHECK-NEXT: MADE{6}:ctor
//CHECK-NEXT: MADE{7}:ctor

gCling->evaluate("arrV", V);
// Now V gets destructed...
//CHECK-NEXT: VAR+{4}:dtor
// ...and the elements are copied:
//CHECK-NEXT: MADE+{8}:copy
//CHECK-NEXT: MADE+{9}:copy
//CHECK-NEXT: MADE+{10}:copy

V // CHECK-NEXT: (cling::Value &) boxes [(Tracer [3]) { @{{.*}}, @{{.*}}, @{{.*}} }]

// Destruct the variables with static storage:
// Destruct arrV:
//CHECK-NEXT: MADE{7}:dtor
//CHECK-NEXT: MADE{6}:dtor
//CHECK-NEXT: MADE{5}:dtor

// CHECK-NEXT: VAR{3}:dtor
// CHECK-NEXT: REF{1}:dtor

//CHECK-NEXT: MADE+{8}:dtor
//CHECK-NEXT: MADE+{9}:dtor
//CHECK-NEXT: MADE+{10}:dtor

<|endoftext|>


<commit_before>// 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.

// This file contains the default suppressions for LeakSanitizer.
// You can also pass additional suppressions via LSAN_OPTIONS:
// LSAN_OPTIONS=suppressions=/path/to/suppressions. Please refer to
// http://dev.chromium.org/developers/testing/leaksanitizer for more info.

#if defined(LEAK_SANITIZER)

// Please make sure the code below declares a single string variable
// kLSanDefaultSuppressions which contains LSan suppressions delimited by
// newlines. See http://dev.chromium.org/developers/testing/leaksanitizer
// for the instructions on writing suppressions.
char kLSanDefaultSuppressions[] =
// Intentional leak used as sanity test for Valgrind/memcheck.
"leak:base::ToolsSanityTest_MemoryLeak_Test::TestBody\n"

// ================ Leaks in third-party code ================

// False positives in libfontconfig. http://crbug.com/39050
"leak:libfontconfig\n"

// Leaks in Nvidia's libGL.
"leak:libGL.so\n"

// A small leak in V8. http://crbug.com/46571#c9
"leak:blink::V8GCController::collectGarbage\n"

// TODO(earthdok): revisit NSS suppressions after the switch to BoringSSL
// NSS leaks in CertDatabaseNSSTest tests. http://crbug.com/51988
"leak:net::NSSCertDatabase::ImportFromPKCS12\n"
"leak:net::NSSCertDatabase::ListCerts\n"
"leak:net::NSSCertDatabase::DeleteCertAndKey\n"
"leak:crypto::ScopedTestNSSDB::ScopedTestNSSDB\n"
// Another leak due to not shutting down NSS properly. http://crbug.com/124445
"leak:error_get_my_stack\n"
// The NSS suppressions above will not fire when the fast stack unwinder is
// used, because it can't unwind through NSS libraries. Apply blanket
// suppressions for now.
"leak:libnssutil3\n"
"leak:libnspr4\n"
"leak:libnss3\n"
"leak:libplds4\n"
"leak:libnssckbi\n"

// XRandR has several one time leaks.
"leak:libxrandr\n"

// xrandr leak. http://crbug.com/119677
"leak:XRRFindDisplay\n"

// Suppressions for objects which can be owned by the V8 heap. This is a
// temporary workaround until LeakSanitizer supports the V8 heap.
// Those should only fire in (browser)tests. If you see one of them in Chrome,
// then it's a real leak.
// http://crbug.com/328552
"leak:WTF::StringImpl::createUninitialized\n"
"leak:WTF::StringImpl::create8BitIfPossible\n"
"leak:blink::MouseEvent::create\n"
"leak:blink::WindowProxy::initializeIfNeeded\n"
"leak:blink::*::*GetterCallback\n"
"leak:blink::CSSComputedStyleDeclaration::create\n"
"leak:blink::V8PerIsolateData::ensureDomInJSContext\n"
"leak:gin/object_template_builder.h\n"
"leak:gin::internal::Dispatcher\n"
"leak:blink::LocalDOMWindow::getComputedStyle\n"
"leak:blink::RemoteDOMWindow::create\n"

// http://crbug.com/356785
"leak:content::RenderViewImplTest_DecideNavigationPolicyForWebUI_Test::TestBody\n"

// ================ Leaks in Chromium code ================
// PLEASE DO NOT ADD SUPPRESSIONS FOR NEW LEAKS.
// Instead, commits that introduce memory leaks should be reverted. Suppressing
// the leak is acceptable in some cases when reverting is impossible, i.e. when
// enabling leak detection for the first time for a test target with
// pre-existing leaks.

// Small test-only leak in ppapi_unittests. http://crbug.com/258113
"leak:ppapi::proxy::PPP_Instance_Private_ProxyTest_PPPInstancePrivate_Test\n"

// http://crbug.com/322671
"leak:content::SpeechRecognitionBrowserTest::SetUpOnMainThread\n"

// http://crbug.com/355641
"leak:TrayAccessibilityTest\n"

// http://crbug.com/354644
"leak:CertificateViewerUITest::ShowModalCertificateViewer\n"

// http://crbug.com/356306
"leak:content::SetProcessTitleFromCommandLine\n"

// PLEASE READ ABOVE BEFORE ADDING NEW SUPPRESSIONS.

// End of suppressions.
;  // Please keep this semicolon.

#endif  // LEAK_SANITIZER
<commit_msg>Fix suppression for RemoteDOMWindow to match on release builds too.<commit_after>// 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.

// This file contains the default suppressions for LeakSanitizer.
// You can also pass additional suppressions via LSAN_OPTIONS:
// LSAN_OPTIONS=suppressions=/path/to/suppressions. Please refer to
// http://dev.chromium.org/developers/testing/leaksanitizer for more info.

#if defined(LEAK_SANITIZER)

// Please make sure the code below declares a single string variable
// kLSanDefaultSuppressions which contains LSan suppressions delimited by
// newlines. See http://dev.chromium.org/developers/testing/leaksanitizer
// for the instructions on writing suppressions.
char kLSanDefaultSuppressions[] =
// Intentional leak used as sanity test for Valgrind/memcheck.
"leak:base::ToolsSanityTest_MemoryLeak_Test::TestBody\n"

// ================ Leaks in third-party code ================

// False positives in libfontconfig. http://crbug.com/39050
"leak:libfontconfig\n"

// Leaks in Nvidia's libGL.
"leak:libGL.so\n"

// A small leak in V8. http://crbug.com/46571#c9
"leak:blink::V8GCController::collectGarbage\n"

// TODO(earthdok): revisit NSS suppressions after the switch to BoringSSL
// NSS leaks in CertDatabaseNSSTest tests. http://crbug.com/51988
"leak:net::NSSCertDatabase::ImportFromPKCS12\n"
"leak:net::NSSCertDatabase::ListCerts\n"
"leak:net::NSSCertDatabase::DeleteCertAndKey\n"
"leak:crypto::ScopedTestNSSDB::ScopedTestNSSDB\n"
// Another leak due to not shutting down NSS properly. http://crbug.com/124445
"leak:error_get_my_stack\n"
// The NSS suppressions above will not fire when the fast stack unwinder is
// used, because it can't unwind through NSS libraries. Apply blanket
// suppressions for now.
"leak:libnssutil3\n"
"leak:libnspr4\n"
"leak:libnss3\n"
"leak:libplds4\n"
"leak:libnssckbi\n"

// XRandR has several one time leaks.
"leak:libxrandr\n"

// xrandr leak. http://crbug.com/119677
"leak:XRRFindDisplay\n"

// Suppressions for objects which can be owned by the V8 heap. This is a
// temporary workaround until LeakSanitizer supports the V8 heap.
// Those should only fire in (browser)tests. If you see one of them in Chrome,
// then it's a real leak.
// http://crbug.com/328552
"leak:WTF::StringImpl::createUninitialized\n"
"leak:WTF::StringImpl::create8BitIfPossible\n"
"leak:blink::MouseEvent::create\n"
"leak:blink::WindowProxy::initializeIfNeeded\n"
"leak:blink::*::*GetterCallback\n"
"leak:blink::CSSComputedStyleDeclaration::create\n"
"leak:blink::V8PerIsolateData::ensureDomInJSContext\n"
"leak:gin/object_template_builder.h\n"
"leak:gin::internal::Dispatcher\n"
"leak:blink::LocalDOMWindow::getComputedStyle\n"
// This should really be RemoteDOMWindow::create, but symbolization is
// weird in release builds. https://crbug.com/484760
"leak:blink::RemoteFrame::create\n"

// http://crbug.com/356785
"leak:content::RenderViewImplTest_DecideNavigationPolicyForWebUI_Test::TestBody\n"

// ================ Leaks in Chromium code ================
// PLEASE DO NOT ADD SUPPRESSIONS FOR NEW LEAKS.
// Instead, commits that introduce memory leaks should be reverted. Suppressing
// the leak is acceptable in some cases when reverting is impossible, i.e. when
// enabling leak detection for the first time for a test target with
// pre-existing leaks.

// Small test-only leak in ppapi_unittests. http://crbug.com/258113
"leak:ppapi::proxy::PPP_Instance_Private_ProxyTest_PPPInstancePrivate_Test\n"

// http://crbug.com/322671
"leak:content::SpeechRecognitionBrowserTest::SetUpOnMainThread\n"

// http://crbug.com/355641
"leak:TrayAccessibilityTest\n"

// http://crbug.com/354644
"leak:CertificateViewerUITest::ShowModalCertificateViewer\n"

// http://crbug.com/356306
"leak:content::SetProcessTitleFromCommandLine\n"

// PLEASE READ ABOVE BEFORE ADDING NEW SUPPRESSIONS.

// End of suppressions.
;  // Please keep this semicolon.

#endif  // LEAK_SANITIZER
<|endoftext|>