diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 552a5c3585..e9ab7fbc52 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -7,10 +7,19 @@ * [CMake](https://cmake.org/) v3.10.0 or later * [Xcode](https://developer.apple.com/xcode/) (10.12) or later (Running on macOS or iOS) * [Android NDK](https://developer.android.com/studio/projects/install-ndk) version `22.1.7171670` (Running on Android)] -* [Visual Studio 2019 or above](https://visualstudio.microsoft.com/) (Running on Windows) +* [Visual Studio 2019 or later](https://visualstudio.microsoft.com/) (Running on Windows) +* [Rust](https://www.rust-lang.org/) (For building Rust example apps.) ## Get the code: +**Additional configuration for Windows users** + +``` +git config --global core.symlinks true +git config --global core.autocrlf false +``` + + ``` git clone git@github.com:openwebf/webf.git git submodule update --init --recursive @@ -22,41 +31,33 @@ git submodule update --init --recursive $ npm install ``` -## Building bridge - -> Debug is the default build type, if you want to have a release build, please add `:release` after your command. -> -> Exp: Execute `npm run build:bridge:macos:release` to build a release bridge for the macOS platform. +## Prepare -**Windows** +**Windows, Linux, Android** -```shell -$ npm run build:bridge:windows:release -``` +The current C/C++ code build process has been integrated into Flutter's compilation and build pipeline for Windows, Linux, and Android. -**macOS** +Run the following script to generate C/C++ binding code using the code generator: ```shell -$ npm run build:bridge:macos:release +npm run generate_binding_code ``` -**linux** +--- -```shell -$ npm run build:bridge:linux:release -``` +**iOS and macOS** -**iOS** +> The default build type is Debug. To create a release build, add `:release` to your command. +> +> Example: Execute `npm run build:bridge:macos:release` to build a release bridge for macOS. ```shell -$ npm run build:bridge:ios:release +$ npm run build:bridge:ios:release # iOS +$ npm run build:bridge:macos:release # macOS ``` -**Android** +--- -```shell -$ npm run build:bridge:android:release -``` ### Run Example diff --git a/.github/workflows/example_build.yml b/.github/workflows/example_build.yml index da828cb9b4..74bd3c5098 100644 --- a/.github/workflows/example_build.yml +++ b/.github/workflows/example_build.yml @@ -10,7 +10,7 @@ on: env: nodeVersion: "16" cmakeVersion: "3.26.3" - flutterVersion: "3.13.5" + flutterVersion: "3.24.0" jobs: build_windows-app_in_windows: @@ -54,7 +54,7 @@ jobs: - uses: actions/setup-java@v3 with: distribution: "temurin" - java-version: "11" + java-version: "17" - uses: jwlawson/actions-setup-cmake@v1.11 with: cmake-version: ${{ env.cmakeVersion }} diff --git a/.gitmodules b/.gitmodules index 5fb940856d..20b258b67a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,7 @@ [submodule "bridge/third_party/quickjs/vendor/mimalloc"] path = bridge/third_party/quickjs/vendor/mimalloc url = https://github.com/microsoft/mimalloc - tag = v1.7.9 \ No newline at end of file + tag = v1.7.9 +[submodule "bridge/third_party/quickjs/compat/win32/pthread-win32"] + path = bridge/third_party/quickjs/compat/win32/pthread-win32 + url = git@github.com:GerHobbelt/pthread-win32.git diff --git a/bridge/CMakeLists.txt b/bridge/CMakeLists.txt index 85d9171f2f..04ae76b75c 100644 --- a/bridge/CMakeLists.txt +++ b/bridge/CMakeLists.txt @@ -21,11 +21,11 @@ if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64") endif() -if(WIN32) - set(PTHREADS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/pthreads") - include_directories(${PTHREADS_ROOT}/include) - link_directories(${PTHREADS_ROOT}/lib/x64) +set(WEBF_JS_ENGINE $ENV{WEBF_JS_ENGINE}) +if(NOT WEBF_JS_ENGINE) + set(WEBF_JS_ENGINE "quickjs") endif() + find_package(Threads REQUIRED) if(MSVC) @@ -80,11 +80,8 @@ if (ENABLE_ASAN) add_link_options(-fsanitize=address -fno-omit-frame-pointer) endif () -if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") - if (MSVC) - set(CMAKE_CXX_FLAGS_RELEASE "/O1") - set(CMAKE_C_FLAGS_RELEASE "/O1") - else() +if (NOT MSVC) + if (${CMAKE_BUILD_TYPE} STREQUAL "Debug") # Avoid quickjs stackoverflow. add_compile_options(-O1) endif() @@ -109,6 +106,7 @@ list(APPEND BRIDGE_SOURCE foundation/stop_watch.cc foundation/profiler.cc foundation/dart_readable.cc + foundation/rust_readable.cc foundation/ui_command_buffer.cc foundation/ui_command_strategy.cc polyfill/dist/polyfill.cc @@ -138,11 +136,12 @@ list(APPEND BRIDGE_INCLUDE ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIST_DIR}/include ${CMAKE_CURRENT_LIST_DIR}/polyfill/dist + ${CMAKE_CURRENT_LIST_DIR}/core_rs/include ${CMAKE_CURRENT_LIST_DIR}/third_party/dart ${ADDITIONAL_INCLUDE_DIRS} ) -if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") +if (${WEBF_JS_ENGINE} MATCHES "quickjs") add_compile_options(-DWEBF_QUICK_JS_ENGINE=1) execute_process( @@ -212,8 +211,33 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") add_library(quickjs SHARED ${QUICK_JS_SOURCE}) endif() + # PThread compact + if(MSVC) + # Using `add_subdirectory` will failed at cmake install starge due to unknown issues: + # https://github.com/flutter/flutter/issues/95530 + set(PTHREADS_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/pthread-win32") + add_library(pthreadVC3 SHARED ${PTHREADS_ROOT}/pthread-JMP.c ${PTHREADS_ROOT}/version.rc) + target_compile_definitions(pthreadVC3 + PRIVATE + _UNICODE + UNICODE + WIN32 + _WINDOWS + _WINDLL + PTW32_CLEANUP_C + UNICODE + _UNICODE + ENABLE_LOG=0 + PTW32_ARCHAMD64 + PTW32_BUILD_INLINED + HAVE_CONFIG_H + PTW32_RC_MSC + ) + target_include_directories(pthreadVC3 PUBLIC ${PTHREADS_ROOT}) + endif() + if(WIN32) - target_link_libraries(quickjs pthreadVC2) + target_link_libraries(quickjs pthreadVC3) target_include_directories(quickjs PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/atomic) target_compile_definitions(quickjs PUBLIC HAVE_STRUCT_TIMESPEC=1 _HAS_EXCEPTIONS=1) else() @@ -221,7 +245,7 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") endif() set(MI_OVERRIDE OFF) - if (NOT DEFINED USE_SYSTEM_MALLOC) + if (NOT MSVC AND NOT DEFINED USE_SYSTEM_MALLOC) add_compile_definitions(ENABLE_MI_MALLOC=1) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/vendor/mimalloc) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/vendor/mimalloc/include) @@ -231,7 +255,7 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") target_include_directories(quickjs PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/include) if (MSVC) - target_include_directories(quickjs PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/pthreads) + target_include_directories(quickjs PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/pthread-win32) target_include_directories(quickjs PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/third_party/quickjs/compat/win32/atomic) endif() @@ -265,12 +289,27 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") bindings/qjs/union_base.cc # Core sources webf_bridge.cc - core/api/api.cc core/executing_context.cc core/script_forbidden_scope.cc core/script_state.cc core/page.cc core/dart_methods.cc + core/api/exception_state.cc + core/api/event_target.cc + core/api/node.cc + core/api/executing_context.cc + core/api/container_node.cc + core/api/document.cc + core/api/element.cc + core/api/html_element.cc + core/api/html_image_element.cc + core/api/html_canvas_element.cc + core/api/document_fragment.cc + core/api/window.cc + core/api/text.cc + core/api/comment.cc + core/api/character_data.cc + core/api/script_value_ref.cc core/dart_isolate_context.cc core/dart_context_data.cc core/executing_context_data.cc @@ -379,6 +418,9 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") core/html/forms/html_form_element.cc core/html/forms/html_textarea_element.cc + core/native/native_loader.cc + core/native/script_value_ref.cc + # SVG files core/svg/svg_element.cc core/svg/svg_graphics_element.cc @@ -475,6 +517,7 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") out/qjs_css_style_declaration.cc out/qjs_inline_css_style_declaration.cc out/qjs_computed_css_style_declaration.cc + out/qjs_native_loader.cc out/qjs_text.cc out/qjs_screen.cc out/qjs_node_list.cc @@ -554,6 +597,21 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") out/qjs_svg_ellipse_element.cc out/qjs_svg_style_element.cc out/qjs_svg_line_element.cc + + # plugin api + out/plugin_api_event.cc + out/plugin_api_animation_event.cc + out/plugin_api_close_event.cc + out/plugin_api_focus_event.cc + out/plugin_api_gesture_event.cc + out/plugin_api_hashchange_event.cc + out/plugin_api_input_event.cc + out/plugin_api_intersection_change_event.cc + out/plugin_api_mouse_event.cc + out/plugin_api_pointer_event.cc + out/plugin_api_transition_event.cc + out/plugin_api_ui_event.cc + out/plugin_api_custom_event.cc ) @@ -571,7 +629,6 @@ list(APPEND PUBLIC_HEADER ) add_library(webf SHARED ${BRIDGE_SOURCE}) -add_library(webf_static STATIC ${BRIDGE_SOURCE}) if(MSVC) target_compile_options(webf PRIVATE /JMC) @@ -596,7 +653,7 @@ elseif(${IS_IOS}) endif() -### webf +## webf target_include_directories(webf PRIVATE ${BRIDGE_INCLUDE} ${CMAKE_CURRENT_SOURCE_DIR} PUBLIC ./include) @@ -612,12 +669,6 @@ if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs" AND NOT MSVC) endif () endif () -### webfStatic -target_include_directories(webf_static PRIVATE - ${BRIDGE_INCLUDE} - ${CMAKE_CURRENT_SOURCE_DIR} PUBLIC ./include) -target_link_libraries(webf_static ${BRIDGE_LINK_LIBS}) - execute_process( COMMAND node get_app_ver.js WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/scripts @@ -644,9 +695,6 @@ if (DEFINED ENV{LIBRARY_OUTPUT_DIR}) LIBRARY_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}" RUNTIME_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}" ) - set_target_properties(webf_static - PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}") - if ($ENV{WEBF_JS_ENGINE} MATCHES "quickjs") set_target_properties(quickjs PROPERTIES @@ -654,8 +702,11 @@ if (DEFINED ENV{LIBRARY_OUTPUT_DIR}) RUNTIME_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}" ) if(MSVC) - set(PTHREAD_LIB ${PTHREADS_ROOT}/dll/x64/pthreadVC2.dll) - file(COPY ${PTHREAD_LIB} DESTINATION "$ENV{LIBRARY_OUTPUT_DIR}") + set_target_properties(pthreadVC3 + PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}" + RUNTIME_OUTPUT_DIRECTORY "$ENV{LIBRARY_OUTPUT_DIR}" + ) endif() endif () elseif (IS_ANDROID) diff --git a/bridge/bindings/qjs/atomic_string.h b/bridge/bindings/qjs/atomic_string.h index f0555c44d8..6cc0c53e35 100644 --- a/bridge/bindings/qjs/atomic_string.h +++ b/bridge/bindings/qjs/atomic_string.h @@ -118,7 +118,7 @@ bool AtomicString::ContainsOnlyLatin1OrEmpty() const { const uint16_t* characters = Character16(); uint16_t ored = 0; - for (size_t i = 0; i < length_; ++i) + for (int64_t i = 0; i < length_; ++i) ored |= characters[i]; return !(ored & 0xFF00); } diff --git a/bridge/bindings/qjs/binding_initializer.cc b/bridge/bindings/qjs/binding_initializer.cc index 3a25fbc33f..f818eb5fae 100644 --- a/bridge/bindings/qjs/binding_initializer.cc +++ b/bridge/bindings/qjs/binding_initializer.cc @@ -53,6 +53,7 @@ #include "qjs_html_template_element.h" #include "qjs_html_textarea_element.h" #include "qjs_html_unknown_element.h" +#include "qjs_hybrid_router_change_event.h" #include "qjs_image.h" #include "qjs_inline_css_style_declaration.h" #include "qjs_input_event.h" @@ -65,6 +66,7 @@ #include "qjs_mutation_observer.h" #include "qjs_mutation_observer_registration.h" #include "qjs_mutation_record.h" +#include "qjs_native_loader.h" #include "qjs_node.h" #include "qjs_node_list.h" #include "qjs_performance.h" @@ -92,7 +94,6 @@ #include "qjs_text.h" #include "qjs_touch.h" #include "qjs_touch_event.h" -#include "qjs_hybrid_router_change_event.h" #include "qjs_touch_list.h" #include "qjs_transition_event.h" #include "qjs_ui_event.h" @@ -199,6 +200,7 @@ void InstallBindings(ExecutingContext* context) { QJSSVGEllipseElement::Install(context); QJSSVGStyleElement::Install(context); QJSSVGLineElement::Install(context); + QJSNativeLoader::Install(context); // Legacy bindings, not standard. QJSElementAttributes::Install(context); diff --git a/bridge/bindings/qjs/converter_impl.h b/bridge/bindings/qjs/converter_impl.h index b02ca3f0a2..746fed42d1 100644 --- a/bridge/bindings/qjs/converter_impl.h +++ b/bridge/bindings/qjs/converter_impl.h @@ -189,7 +189,7 @@ struct Converter : public ConverterBase { JS_ToInt64(ctx, &v, value); return v; } - static JSValue ToValue(JSContext* ctx, uint32_t v) { return JS_NewInt64(ctx, v); } + static JSValue ToValue(JSContext* ctx, int64_t v) { return JS_NewInt64(ctx, v); } }; template <> @@ -219,7 +219,7 @@ struct Converter : public ConverterBase { return JS_NewUnicodeString(ctx, str->string(), str->length()); } static JSValue ToValue(JSContext* ctx, uint16_t* bytes, size_t length) { - return JS_NewUnicodeString(ctx, bytes, length); + return JS_NewUnicodeString(ctx, bytes, static_cast(length)); } static JSValue ToValue(JSContext* ctx, const std::string& str) { return JS_NewString(ctx, str.c_str()); } }; diff --git a/bridge/bindings/qjs/exception_state.cc b/bridge/bindings/qjs/exception_state.cc index 48430aa552..0d6d8d351c 100644 --- a/bridge/bindings/qjs/exception_state.cc +++ b/bridge/bindings/qjs/exception_state.cc @@ -3,9 +3,14 @@ * Copyright (C) 2022-present The WebF authors. All rights reserved. */ #include "exception_state.h" +#include "plugin_api/exception_state.h" namespace webf { +ExceptionStatePublicMethods* ExceptionState::publicMethodPointer() { + return new ExceptionStatePublicMethods(); +} + void ExceptionState::ThrowException(JSContext* ctx, ErrorType type, const std::string& message) { switch (type) { case ErrorType::TypeError: diff --git a/bridge/bindings/qjs/exception_state.h b/bridge/bindings/qjs/exception_state.h index edf36a3bf7..43fcc9890e 100644 --- a/bridge/bindings/qjs/exception_state.h +++ b/bridge/bindings/qjs/exception_state.h @@ -13,6 +13,8 @@ namespace webf { +class ExceptionStatePublicMethods; + enum ErrorType { TypeError, InternalError, RangeError, ReferenceError, SyntaxError }; // ExceptionState is a scope-like class and provides a way to store an exception. @@ -21,6 +23,8 @@ class ExceptionState { WEBF_DISALLOW_NEW(); public: + static ExceptionStatePublicMethods* publicMethodPointer(); + void ThrowException(JSContext* ctx, ErrorType type, const std::string& message); void ThrowException(JSContext* ctx, JSValue exception); bool HasException(); diff --git a/bridge/bindings/qjs/idl_type.h b/bridge/bindings/qjs/idl_type.h index ef99f3dfa9..f1aa63b9f0 100644 --- a/bridge/bindings/qjs/idl_type.h +++ b/bridge/bindings/qjs/idl_type.h @@ -40,7 +40,7 @@ struct IDLBoolean final : public IDLTypeBaseHelper {}; // Primitive types struct IDLInt32 final : public IDLTypeBaseHelper {}; -struct IDLInt64 final : public IDLTypeBaseHelper {}; +struct IDLInt64 final : public IDLTypeBaseHelper {}; struct IDLUint32 final : public IDLTypeBaseHelper {}; struct IDLDouble final : public IDLTypeBaseHelper {}; diff --git a/bridge/bindings/qjs/js_event_handler.cc b/bridge/bindings/qjs/js_event_handler.cc index 937e528619..c1f1912010 100644 --- a/bridge/bindings/qjs/js_event_handler.cc +++ b/bridge/bindings/qjs/js_event_handler.cc @@ -76,7 +76,8 @@ void JSEventHandler::InvokeInternal(EventTarget& event_target, Event& event, Exc arguments.emplace_back(event.ToValue()); } - ScriptValue result = event_handler_->Invoke(event.ctx(), event_target.ToValue(), arguments.size(), arguments.data()); + ScriptValue result = + event_handler_->Invoke(event.ctx(), event_target.ToValue(), (int)arguments.size(), arguments.data()); if (result.IsException()) { exception_state.ThrowException(event.ctx(), result.QJSValue()); return; diff --git a/bridge/bindings/qjs/member_installer.cc b/bridge/bindings/qjs/member_installer.cc index ffece4d1b4..4a23a1117a 100644 --- a/bridge/bindings/qjs/member_installer.cc +++ b/bridge/bindings/qjs/member_installer.cc @@ -73,7 +73,7 @@ void MemberInstaller::InstallFunctions(ExecutingContext* context, std::initializer_list config) { JSContext* ctx = context->ctx(); for (auto& c : config) { - JSValue function = JS_NewCFunction(ctx, c.function, c.name, c.length); + JSValue function = JS_NewCFunction(ctx, c.function, c.name, (int)c.length); JS_DefinePropertyValueStr(ctx, root, c.name, function, c.flag); } } diff --git a/bridge/bindings/qjs/qjs_engine_patch.h b/bridge/bindings/qjs/qjs_engine_patch.h index bedf959aed..58f23df750 100644 --- a/bridge/bindings/qjs/qjs_engine_patch.h +++ b/bridge/bindings/qjs/qjs_engine_patch.h @@ -6,6 +6,9 @@ #ifndef BRIDGE_QJS_PATCH_H #define BRIDGE_QJS_PATCH_H +#pragma warning(push) +#pragma warning(disable : 4200) + #include #include #include "foundation/string_view.h" diff --git a/bridge/bindings/qjs/qjs_function.cc b/bridge/bindings/qjs/qjs_function.cc index 71c44e224d..299bf86b66 100644 --- a/bridge/bindings/qjs/qjs_function.cc +++ b/bridge/bindings/qjs/qjs_function.cc @@ -47,7 +47,7 @@ bool QJSFunction::IsFunction(JSContext* ctx) { return JS_IsFunction(ctx, function_); } -ScriptValue QJSFunction::Invoke(JSContext* ctx, const ScriptValue& this_val, int32_t argc, ScriptValue* arguments) { +ScriptValue QJSFunction::Invoke(JSContext* ctx, const ScriptValue& this_val, int argc, ScriptValue* arguments) { // 'm_function' might be destroyed when calling itself (if it frees the handler), so must take extra care. JS_DupValue(ctx, function_); diff --git a/bridge/bindings/qjs/script_wrappable.cc b/bridge/bindings/qjs/script_wrappable.cc index 7f1dab538f..d830f04b22 100644 --- a/bridge/bindings/qjs/script_wrappable.cc +++ b/bridge/bindings/qjs/script_wrappable.cc @@ -18,6 +18,12 @@ ScriptWrappable::ScriptWrappable(JSContext* ctx) context_(ExecutingContext::From(ctx)), context_id_(context_->contextId()) {} +ScriptWrappable::~ScriptWrappable() { + if (status_block_ != nullptr) { + status_block_->disposed = true; + } +} + JSValue ScriptWrappable::ToQuickJS() const { return JS_DupValue(ctx_, jsObject_); } @@ -295,21 +301,24 @@ void ScriptWrappable::InitializeQuickJSObject() { JS_SetPrototype(ctx_, jsObject_, prototype); } -void ScriptWrappable::KeepAlive() { - if (is_alive) - return; - - context_->RegisterActiveScriptWrappers(this); - JS_DupValue(ctx_, jsObject_); - is_alive = true; +WebFValueStatus* ScriptWrappable::KeepAlive() { + if (alive_count == 0) { + context_->RegisterActiveScriptWrappers(this); + JS_DupValue(ctx_, jsObject_); + status_block_ = new WebFValueStatus(); + } + alive_count++; + return status_block_; } void ScriptWrappable::ReleaseAlive() { - if (!is_alive) - return; - context_->InActiveScriptWrappers(this); - JS_FreeValue(ctx_, jsObject_); - is_alive = false; + alive_count--; + if (alive_count == 0) { + context_->InActiveScriptWrappers(this); + JS_FreeValue(ctx_, jsObject_); + delete status_block_; + status_block_ = nullptr; + } } } // namespace webf diff --git a/bridge/bindings/qjs/script_wrappable.h b/bridge/bindings/qjs/script_wrappable.h index c6d5fe176b..6f6c9f3728 100644 --- a/bridge/bindings/qjs/script_wrappable.h +++ b/bridge/bindings/qjs/script_wrappable.h @@ -10,6 +10,7 @@ #include "bindings/qjs/cppgc/garbage_collected.h" #include "foundation/macros.h" #include "multiple_threading/dispatcher.h" +#include "plugin_api/webf_value.h" #include "wrapper_type_info.h" namespace webf { @@ -41,7 +42,7 @@ class ScriptWrappable : public GarbageCollected { ScriptWrappable() = delete; explicit ScriptWrappable(JSContext* ctx); - virtual ~ScriptWrappable() = default; + virtual ~ScriptWrappable(); // Returns the WrapperTypeInfo of the instance. virtual const WrapperTypeInfo* GetWrapperTypeInfo() const = 0; @@ -56,7 +57,7 @@ class ScriptWrappable : public GarbageCollected { multi_threading::Dispatcher* GetDispatcher() const; FORCE_INLINE JSContext* ctx() const { return ctx_; } FORCE_INLINE JSRuntime* runtime() const { return runtime_; } - FORCE_INLINE int64_t contextId() const { return context_id_; } + FORCE_INLINE double contextId() const { return context_id_; } void InitializeQuickJSObject() override; @@ -64,16 +65,17 @@ class ScriptWrappable : public GarbageCollected { * Classes kept alive as long as they have a pending activity. * Release them via `ReleaseAlive` method. */ - void KeepAlive(); + WebFValueStatus* KeepAlive(); void ReleaseAlive(); private: - bool is_alive = false; + uint32_t alive_count = 0; JSValue jsObject_{JS_NULL}; JSContext* ctx_{nullptr}; ExecutingContext* context_{nullptr}; - int64_t context_id_; + double context_id_; JSRuntime* runtime_{nullptr}; + WebFValueStatus* status_block_{nullptr}; friend class GCVisitor; }; diff --git a/bridge/bindings/qjs/wrapper_type_info.h b/bridge/bindings/qjs/wrapper_type_info.h index 3aa7c313ad..90245bf162 100644 --- a/bridge/bindings/qjs/wrapper_type_info.h +++ b/bridge/bindings/qjs/wrapper_type_info.h @@ -94,6 +94,8 @@ enum { JS_CLASS_DOM_TOKEN_LIST, JS_CLASS_DOM_STRING_MAP, + JS_CLASS_NATIVE_LOADER, + // SVG JS_CLASS_SVG_ELEMENT, JS_CLASS_SVG_GRAPHICS_ELEMENT, diff --git a/bridge/core/api/api.cc b/bridge/core/api/api.cc deleted file mode 100644 index f5ccd95ff8..0000000000 --- a/bridge/core/api/api.cc +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (C) 2022-present The WebF authors. All rights reserved. - */ - -#include "api.h" -#include "core/dart_isolate_context.h" -#include "core/html/parser/html_parser.h" -#include "core/page.h" -#include "multiple_threading/dispatcher.h" - -namespace webf { - -static void ReturnEvaluateScriptsInternal(Dart_PersistentHandle persistent_handle, - EvaluateQuickjsByteCodeCallback result_callback, - bool is_success) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); - result_callback(handle, is_success ? 1 : 0); - Dart_DeletePersistentHandle_DL(persistent_handle); -} - -void evaluateScriptsInternal(void* page_, - const char* code, - uint64_t code_len, - uint8_t** parsed_bytecodes, - uint64_t* bytecode_len, - const char* bundleFilename, - int32_t startLine, - int64_t profile_id, - Dart_Handle persistent_handle, - EvaluateScriptsCallback result_callback) { - auto page = reinterpret_cast(page_); - assert(std::this_thread::get_id() == page->currentThread()); - - page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); - - bool is_success = page->evaluateScript(code, code_len, parsed_bytecodes, bytecode_len, bundleFilename, startLine); - - page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); - - page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnEvaluateScriptsInternal, - persistent_handle, result_callback, is_success); -} - -static void ReturnEvaluateQuickjsByteCodeResultToDart(Dart_PersistentHandle persistent_handle, - EvaluateQuickjsByteCodeCallback result_callback, - bool is_success) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); - result_callback(handle, is_success ? 1 : 0); - Dart_DeletePersistentHandle_DL(persistent_handle); -} - -void evaluateQuickjsByteCodeInternal(void* page_, - uint8_t* bytes, - int32_t byteLen, - int64_t profile_id, - Dart_PersistentHandle persistent_handle, - EvaluateQuickjsByteCodeCallback result_callback) { - auto page = reinterpret_cast(page_); - assert(std::this_thread::get_id() == page->currentThread()); - - page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); - - bool is_success = page->evaluateByteCode(bytes, byteLen); - - page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); - - page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnEvaluateQuickjsByteCodeResultToDart, - persistent_handle, result_callback, is_success); -} - -static void ReturnParseHTMLToDart(Dart_PersistentHandle persistent_handle, ParseHTMLCallback result_callback) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); - result_callback(handle); - Dart_DeletePersistentHandle_DL(persistent_handle); -} - -void parseHTMLInternal(void* page_, - char* code, - int32_t length, - int64_t profile_id, - Dart_PersistentHandle dart_handle, - ParseHTMLCallback result_callback) { - auto page = reinterpret_cast(page_); - assert(std::this_thread::get_id() == page->currentThread()); - - page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); - - page->parseHTML(code, length); - dart_free(code); - - page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); - - page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnParseHTMLToDart, dart_handle, - result_callback); -} - -static void ReturnInvokeEventResultToDart(Dart_Handle persistent_handle, - InvokeModuleEventCallback result_callback, - webf::NativeValue* result) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); - result_callback(handle, result); - Dart_DeletePersistentHandle_DL(persistent_handle); -} - -void invokeModuleEventInternal(void* page_, - void* module_name, - const char* eventType, - void* event, - void* extra, - Dart_Handle persistent_handle, - InvokeModuleEventCallback result_callback) { - auto page = reinterpret_cast(page_); - auto dart_isolate_context = page->executingContext()->dartIsolateContext(); - assert(std::this_thread::get_id() == page->currentThread()); - - page->dartIsolateContext()->profiler()->StartTrackAsyncEvaluation(); - - auto* result = page->invokeModuleEvent(reinterpret_cast(module_name), eventType, event, - reinterpret_cast(extra)); - - page->dartIsolateContext()->profiler()->FinishTrackAsyncEvaluation(); - - dart_isolate_context->dispatcher()->PostToDart(page->isDedicated(), ReturnInvokeEventResultToDart, persistent_handle, - result_callback, result); -} - -static void ReturnDumpByteCodeResultToDart(Dart_Handle persistent_handle, DumpQuickjsByteCodeCallback result_callback) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); - result_callback(handle); - Dart_DeletePersistentHandle_DL(persistent_handle); -} - -void dumpQuickJsByteCodeInternal(void* page_, - int64_t profile_id, - const char* code, - int32_t code_len, - uint8_t** parsed_bytecodes, - uint64_t* bytecode_len, - const char* url, - Dart_PersistentHandle persistent_handle, - DumpQuickjsByteCodeCallback result_callback) { - auto page = reinterpret_cast(page_); - auto dart_isolate_context = page->executingContext()->dartIsolateContext(); - - dart_isolate_context->profiler()->StartTrackEvaluation(profile_id); - - assert(std::this_thread::get_id() == page->currentThread()); - uint8_t* bytes = page->dumpByteCode(code, code_len, url, bytecode_len); - *parsed_bytecodes = bytes; - - dart_isolate_context->profiler()->FinishTrackEvaluation(profile_id); - - dart_isolate_context->dispatcher()->PostToDart(page->isDedicated(), ReturnDumpByteCodeResultToDart, persistent_handle, - result_callback); -} - -} // namespace webf diff --git a/bridge/core/api/api.h b/bridge/core/api/api.h deleted file mode 100644 index ee6273d668..0000000000 --- a/bridge/core/api/api.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2022-present The WebF authors. All rights reserved. - */ - -#ifndef WEBF_CORE_API_API_H_ -#define WEBF_CORE_API_API_H_ - -#include -#include "include/webf_bridge.h" - -namespace webf { - -void evaluateScriptsInternal(void* page_, - const char* code, - uint64_t code_len, - uint8_t** parsed_bytecodes, - uint64_t* bytecode_len, - const char* bundleFilename, - int32_t startLine, - int64_t profile_id, - Dart_Handle dart_handle, - EvaluateScriptsCallback result_callback); - -void evaluateQuickjsByteCodeInternal(void* page_, - uint8_t* bytes, - int32_t byteLen, - int64_t profile_id, - Dart_PersistentHandle persistent_handle, - EvaluateQuickjsByteCodeCallback result_callback); -void parseHTMLInternal(void* page_, - char* code, - int32_t length, - int64_t profile_id, - Dart_PersistentHandle dart_handle, - ParseHTMLCallback result_callback); - -void invokeModuleEventInternal(void* page_, - void* module_name, - const char* eventType, - void* event, - void* extra, - Dart_Handle dart_handle, - InvokeModuleEventCallback result_callback); - -void dumpQuickJsByteCodeInternal(void* page_, - int64_t profile_id, - const char* code, - int32_t code_len, - uint8_t** parsed_bytecodes, - uint64_t* bytecode_len, - const char* url, - Dart_PersistentHandle persistent_handle, - DumpQuickjsByteCodeCallback result_callback); - -} // namespace webf - -#endif // WEBF_CORE_API_API_H_ diff --git a/bridge/core/api/character_data.cc b/bridge/core/api/character_data.cc new file mode 100644 index 0000000000..442cf64f30 --- /dev/null +++ b/bridge/core/api/character_data.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/character_data.h" +#include "core/dom/node.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/comment.cc b/bridge/core/api/comment.cc new file mode 100644 index 0000000000..4308aa0aa2 --- /dev/null +++ b/bridge/core/api/comment.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/comment.h" +#include "core/dom/character_data.h" + +namespace webf {} // namespace webf diff --git a/bridge/core/api/container_node.cc b/bridge/core/api/container_node.cc new file mode 100644 index 0000000000..13aa3ece50 --- /dev/null +++ b/bridge/core/api/container_node.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/container_node.h" +#include "core/dom/node.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/document.cc b/bridge/core/api/document.cc new file mode 100644 index 0000000000..935144ed05 --- /dev/null +++ b/bridge/core/api/document.cc @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/document.h" +#include "core/api/exception_state.h" +#include "core/dom/comment.h" +#include "core/dom/document.h" +#include "core/dom/document_fragment.h" +#include "core/dom/events/event.h" +#include "core/dom/text.h" +#include "core/html/html_body_element.h" +#include "core/html/html_head_element.h" +#include "core/html/html_html_element.h" + +namespace webf { + +WebFValue DocumentPublicMethods::CreateElement( + webf::Document* ptr, + const char* tag_name, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString tag_name_atomic = webf::AtomicString(document->ctx(), tag_name); + Element* new_element = document->createElement(tag_name_atomic, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + // Hold the reference until rust side notify this element was released. + WebFValueStatus* status_block = new_element->KeepAlive(); + return WebFValue(new_element, new_element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateElementWithElementCreationOptions( + webf::Document* ptr, + const char* tag_name, + WebFElementCreationOptions& options, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString tag_name_atomic = webf::AtomicString(document->ctx(), tag_name); + + std::string value = std::string(R"({"is":")") + options.is + "\"}"; + const char* value_cstr = value.c_str(); + webf::ScriptValue options_value = webf::ScriptValue::CreateJsonObject(document->ctx(), value_cstr, value.length()); + + Element* new_element = + document->createElement(tag_name_atomic, options_value, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + // Hold the reference until rust side notify this element was released. + WebFValueStatus* status_block = new_element->KeepAlive(); + return WebFValue(new_element, new_element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateElementNS( + webf::Document* ptr, + const char* uri, + const char* tag_name, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString uri_atomic = webf::AtomicString(document->ctx(), uri); + webf::AtomicString tag_name_atomic = webf::AtomicString(document->ctx(), tag_name); + Element* new_element = + document->createElementNS(uri_atomic, tag_name_atomic, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + // Hold the reference until rust side notify this element was released. + WebFValueStatus* status_block = new_element->KeepAlive(); + return WebFValue(new_element, new_element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateElementNSWithElementCreationOptions( + webf::Document* ptr, + const char* uri, + const char* tag_name, + WebFElementCreationOptions& options, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString uri_atomic = webf::AtomicString(document->ctx(), uri); + webf::AtomicString tag_name_atomic = webf::AtomicString(document->ctx(), tag_name); + + std::string value = std::string(R"({"is":")") + options.is + "\"}"; + const char* value_cstr = value.c_str(); + webf::ScriptValue options_value = webf::ScriptValue::CreateJsonObject(document->ctx(), value_cstr, value.length()); + + Element* new_element = + document->createElementNS(uri_atomic, tag_name_atomic, options_value, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + // Hold the reference until rust side notify this element was released. + WebFValueStatus* status_block = new_element->KeepAlive(); + return WebFValue(new_element, new_element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateTextNode( + webf::Document* ptr, + const char* data, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString data_atomic = webf::AtomicString(document->ctx(), data); + Text* text_node = document->createTextNode(data_atomic, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = text_node->KeepAlive(); + + return WebFValue(text_node, text_node->textNodePublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateDocumentFragment( + webf::Document* ptr, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + DocumentFragment* document_fragment = document->createDocumentFragment(shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = document_fragment->KeepAlive(); + + return WebFValue( + document_fragment, document_fragment->documentFragmentPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateComment( + webf::Document* ptr, + const char* data, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString data_atomic = webf::AtomicString(document->ctx(), data); + Comment* comment = document->createComment(data_atomic, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = comment->KeepAlive(); + + return WebFValue(comment, comment->commentPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::CreateEvent( + webf::Document* ptr, + const char* type, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString type_atomic = webf::AtomicString(document->ctx(), type); + Event* event = document->createEvent(type_atomic, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = event->KeepAlive(); + + return WebFValue(event, event->eventPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::QuerySelector( + webf::Document* ptr, + const char* selectors, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString selectors_atomic = webf::AtomicString(document->ctx(), selectors); + Element* element = document->querySelector(selectors_atomic, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = element->KeepAlive(); + + return WebFValue(element, element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::GetElementById( + webf::Document* ptr, + const char* id, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + webf::AtomicString id_atomic = webf::AtomicString(document->ctx(), id); + Element* element = document->getElementById(id_atomic, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = element->KeepAlive(); + + return WebFValue(element, element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::ElementFromPoint( + webf::Document* ptr, + double x, + double y, + webf::SharedExceptionState* shared_exception_state) { + auto* document = static_cast(ptr); + MemberMutationScope scope{document->GetExecutingContext()}; + Element* element = document->elementFromPoint(x, y, shared_exception_state->exception_state); + + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = element->KeepAlive(); + + return WebFValue(element, element->elementPublicMethods(), status_block); +} + +WebFValue DocumentPublicMethods::DocumentElement(webf::Document* document) { + auto* document_element = document->documentElement(); + WebFValueStatus* status_block = document_element->KeepAlive(); + return WebFValue{document_element, document_element->htmlElementPublicMethods(), + status_block}; +} + +WebFValue DocumentPublicMethods::Head(webf::Document* document) { + auto* head = document->head(); + WebFValueStatus* status_block = head->KeepAlive(); + return WebFValue{head, head->htmlElementPublicMethods(), status_block}; +} + +WebFValue DocumentPublicMethods::Body(webf::Document* document) { + auto* body = document->body(); + WebFValueStatus* status_block = body->KeepAlive(); + return WebFValue{body, body->htmlElementPublicMethods(), status_block}; +} + +} // namespace webf diff --git a/bridge/core/api/document_fragment.cc b/bridge/core/api/document_fragment.cc new file mode 100644 index 0000000000..89824df5fc --- /dev/null +++ b/bridge/core/api/document_fragment.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/document_fragment.h" +#include "core/dom/container_node.h" + +namespace webf {} // namespace webf diff --git a/bridge/core/api/element.cc b/bridge/core/api/element.cc new file mode 100644 index 0000000000..89b7b4ac0d --- /dev/null +++ b/bridge/core/api/element.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/element.h" +#include "core/dom/container_node.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/event_target.cc b/bridge/core/api/event_target.cc new file mode 100644 index 0000000000..2888dc5b78 --- /dev/null +++ b/bridge/core/api/event_target.cc @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/event_target.h" +#include "bindings/qjs/atomic_string.h" +#include "core/api/exception_state.h" +#include "core/dom/comment.h" +#include "core/dom/container_node.h" +#include "core/dom/document.h" +#include "core/dom/document_fragment.h" +#include "core/dom/element.h" +#include "core/dom/events/event.h" +#include "core/dom/events/event_target.h" +#include "core/dom/node.h" +#include "core/dom/text.h" +#include "core/frame/window.h" +#include "core/html/canvas/html_canvas_element.h" +#include "core/html/html_element.h" +#include "core/html/html_image_element.h" +#include "html_element_type_helper.h" +#include "plugin_api/add_event_listener_options.h" + +namespace webf { + +class WebFPublicPluginEventListener : public EventListener { + public: + WebFPublicPluginEventListener(WebFEventListenerContext* callback_context, + SharedExceptionState* shared_exception_state) + : callback_context_(callback_context), shared_exception_state_(shared_exception_state) {} + + ~WebFPublicPluginEventListener() { + callback_context_->free_ptr(callback_context_); + delete callback_context_; + } + + static const std::shared_ptr Create(WebFEventListenerContext* WebF_event_listener, + SharedExceptionState* shared_exception_state) { + return std::make_shared(WebF_event_listener, shared_exception_state); + }; + + [[nodiscard]] bool IsPublicPluginEventHandler() const override { return true; } + + void Invoke(ExecutingContext* context, Event* event, ExceptionState& exception_state) override { + WebFValueStatus* status_block = event->KeepAlive(); + callback_context_->callback(callback_context_, event, event->eventPublicMethods(), status_block, + shared_exception_state_); + } + + [[nodiscard]] bool Matches(const EventListener& other) const override { + const auto* other_listener = DynamicTo(other); + return other_listener && other_listener->callback_context_ && + other_listener->callback_context_->callback == callback_context_->callback; + } + + void Trace(GCVisitor* visitor) const override {} + + WebFEventListenerContext* callback_context_; + SharedExceptionState* shared_exception_state_; +}; + +template <> +struct DowncastTraits { + static bool AllowFrom(const EventListener& event_listener) { return event_listener.IsPublicPluginEventHandler(); } +}; + +void EventTargetPublicMethods::AddEventListener(EventTarget* event_target, + const char* event_name_str, + WebFEventListenerContext* callback_context, + WebFAddEventListenerOptions* options, + SharedExceptionState* shared_exception_state) { + AtomicString event_name = AtomicString(event_target->ctx(), event_name_str); + std::shared_ptr event_listener_options = AddEventListenerOptions::Create(); + + // Preparing for the event listener options. + event_listener_options->setOnce(options->once); + event_listener_options->setPassive(options->passive); + event_listener_options->setCapture(options->capture); + + auto listener_impl = WebFPublicPluginEventListener::Create(callback_context, shared_exception_state); + + event_target->addEventListener(event_name, listener_impl, event_listener_options, + shared_exception_state->exception_state); +} + +void EventTargetPublicMethods::RemoveEventListener(EventTarget* event_target, + const char* event_name_str, + WebFEventListenerContext* callback_context, + SharedExceptionState* shared_exception_state) { + AtomicString event_name = AtomicString(event_target->ctx(), event_name_str); + auto listener_impl = WebFPublicPluginEventListener::Create(callback_context, shared_exception_state); + + event_target->removeEventListener(event_name, listener_impl, shared_exception_state->exception_state); +} + +bool EventTargetPublicMethods::DispatchEvent(EventTarget* event_target, + Event* event, + SharedExceptionState* shared_exception_state) { + return event_target->dispatchEvent(event, shared_exception_state->exception_state); +} + +void EventTargetPublicMethods::Release(EventTarget* event_target) { + event_target->ReleaseAlive(); +} + +WebFValue EventTargetPublicMethods::DynamicTo(webf::EventTarget* event_target, + webf::EventTargetType event_target_type) { + switch (event_target_type) { + case EventTargetType::kEventTarget: { + WebFValueStatus* status_block = event_target->KeepAlive(); + return WebFValue(event_target, event_target->eventTargetPublicMethods(), + status_block); + } + case EventTargetType::kNode: { + auto* node = webf::DynamicTo(event_target); + if (node == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = node->KeepAlive(); + return WebFValue(node, node->nodePublicMethods(), status_block); + } + case EventTargetType::kContainerNode: { + auto* container_node = webf::DynamicTo(event_target); + if (container_node == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = container_node->KeepAlive(); + return WebFValue(container_node, container_node->containerNodePublicMethods(), + status_block); + } + case EventTargetType::kWindow: { + auto* window = webf::DynamicTo(event_target); + if (window == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = window->KeepAlive(); + return WebFValue(window, window->windowPublicMethods(), status_block); + } + case EventTargetType::kDocument: { + auto* document = webf::DynamicTo(event_target); + if (document == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = document->KeepAlive(); + return WebFValue(document, document->documentPublicMethods(), status_block); + } + case EventTargetType::kElement: { + auto* element = webf::DynamicTo(event_target); + if (element == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = element->KeepAlive(); + return WebFValue(element, element->elementPublicMethods(), status_block); + } + case EventTargetType::kHTMLDivElement: + case EventTargetType::kHTMLScriptElement: + case EventTargetType::HTMLElement: { + auto* html_element = webf::DynamicTo(event_target); + if (html_element == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = html_element->KeepAlive(); + return WebFValue(html_element, html_element->htmlElementPublicMethods(), + status_block); + } + case EventTargetType::kHTMLImageElement: { + auto* html_image_element = webf::DynamicTo(event_target); + if (html_image_element == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = html_image_element->KeepAlive(); + return WebFValue( + html_image_element, html_image_element->htmlImageElementPublicMethods(), status_block); + } + case EventTargetType::kDocumentFragment: { + auto* document_fragment = webf::DynamicTo(event_target); + if (document_fragment == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = document_fragment->KeepAlive(); + return WebFValue( + document_fragment, document_fragment->documentFragmentPublicMethods(), status_block); + } + case EventTargetType::kText: { + auto* text = webf::DynamicTo(event_target); + if (text == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = text->KeepAlive(); + return WebFValue(text, text->textNodePublicMethods(), status_block); + } + case EventTargetType::kComment: { + auto* comment = webf::DynamicTo(event_target); + if (comment == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = comment->KeepAlive(); + return WebFValue(comment, comment->commentPublicMethods(), status_block); + } + case EventTargetType::kHTMLCanvasElement: { + auto* canvas_element = webf::DynamicTo(event_target); + if (canvas_element == nullptr) { + return WebFValue::Null(); + } + WebFValueStatus* status_block = canvas_element->KeepAlive(); + return WebFValue(canvas_element, canvas_element->htmlCanvasElementPublicMethods(), + status_block); + } + default: + assert_m(false, ("Unknown event_target_type " + std::to_string(static_cast(event_target_type))).c_str()); + } +} + +} // namespace webf diff --git a/bridge/core/api/exception_state.cc b/bridge/core/api/exception_state.cc new file mode 100644 index 0000000000..9ffbd71763 --- /dev/null +++ b/bridge/core/api/exception_state.cc @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/exception_state.h" +#include "bindings/qjs/exception_state.h" +#include "core/api/exception_state.h" +#include "core/executing_context.h" + +namespace webf { + +SharedExceptionState::SharedExceptionState() = default; + +bool ExceptionStatePublicMethods::HasException(SharedExceptionState* shared_exception_state) { + return shared_exception_state->exception_state.HasException(); +} + +void ExceptionStatePublicMethods::Stringify(webf::ExecutingContext* context, + webf::SharedExceptionState* shared_exception_state, + char** errmsg, + uint32_t* strlen) { + context->HandleException(shared_exception_state->exception_state, errmsg, strlen); +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/exception_state.h b/bridge/core/api/exception_state.h new file mode 100644 index 0000000000..c1609150c7 --- /dev/null +++ b/bridge/core/api/exception_state.h @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef EXCEPTION_STATE_H +#define EXCEPTION_STATE_H + +#include "bindings/qjs/exception_state.h" +#include "plugin_api/rust_readable.h" + +namespace webf { + +class SharedExceptionState : public RustReadable { + public: + SharedExceptionState(); + + ExceptionState exception_state; +}; + +} // namespace webf + +#endif // EXCEPTION_STATE_H diff --git a/bridge/core/api/executing_context.cc b/bridge/core/api/executing_context.cc new file mode 100644 index 0000000000..85a7e728b1 --- /dev/null +++ b/bridge/core/api/executing_context.cc @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/executing_context.h" +#include "bindings/qjs/exception_state.h" +#include "core/api/exception_state.h" +#include "core/dom/document.h" +#include "core/executing_context.h" +#include "core/frame/window.h" + +namespace webf { + +WebFValue ExecutingContextWebFMethods::document(webf::ExecutingContext* context) { + auto* document = context->document(); + WebFValueStatus* status_block = document->KeepAlive(); + return WebFValue(document, document->documentPublicMethods(), status_block); +} + +WebFValue ExecutingContextWebFMethods::window(webf::ExecutingContext* context) { + return WebFValue(context->window(), context->window()->windowPublicMethods(), + context->window()->KeepAlive()); +} + +WebFValue ExecutingContextWebFMethods::CreateExceptionState() { + return WebFValue(new SharedExceptionState(), + ExceptionState::publicMethodPointer(), nullptr); +} + +} // namespace webf diff --git a/bridge/core/api/html_canvas_element.cc b/bridge/core/api/html_canvas_element.cc new file mode 100644 index 0000000000..f98a4d7b1e --- /dev/null +++ b/bridge/core/api/html_canvas_element.cc @@ -0,0 +1,7 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/html_canvas_element.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/html_element.cc b/bridge/core/api/html_element.cc new file mode 100644 index 0000000000..6c05ca7684 --- /dev/null +++ b/bridge/core/api/html_element.cc @@ -0,0 +1,7 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/html_element.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/html_image_element.cc b/bridge/core/api/html_image_element.cc new file mode 100644 index 0000000000..bb6db33f77 --- /dev/null +++ b/bridge/core/api/html_image_element.cc @@ -0,0 +1,7 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/html_image_element.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/node.cc b/bridge/core/api/node.cc new file mode 100644 index 0000000000..c9f1fbf437 --- /dev/null +++ b/bridge/core/api/node.cc @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/node.h" +#include "core/api/exception_state.h" +#include "core/dom/events/event_target.h" +#include "core/dom/node.h" + +namespace webf { + +NodePublicMethods::NodePublicMethods() {} + +WebFValue NodePublicMethods::AppendChild(Node* self_node, + Node* new_node, + SharedExceptionState* shared_exception_state) { + MemberMutationScope member_mutation_scope{self_node->GetExecutingContext()}; + Node* returned_node = self_node->appendChild(new_node, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = returned_node->KeepAlive(); + return WebFValue(returned_node, returned_node->nodePublicMethods(), status_block); +} + +WebFValue NodePublicMethods::RemoveChild(webf::Node* self_node, + webf::Node* target_node, + webf::SharedExceptionState* shared_exception_state) { + MemberMutationScope member_mutation_scope{self_node->GetExecutingContext()}; + Node* returned_node = target_node->removeChild(target_node, shared_exception_state->exception_state); + if (shared_exception_state->exception_state.HasException()) { + return WebFValue::Null(); + } + + WebFValueStatus* status_block = returned_node->KeepAlive(); + return WebFValue(returned_node, returned_node->nodePublicMethods(), status_block); +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/script_value_ref.cc b/bridge/core/api/script_value_ref.cc new file mode 100644 index 0000000000..9e8dac034b --- /dev/null +++ b/bridge/core/api/script_value_ref.cc @@ -0,0 +1,14 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/script_value_ref.h" +#include "core/native/script_value_ref.h" + +namespace webf { + +void ScriptValueRefPublicMethods::Release(webf::ScriptValueRef* script_value_ref) { + delete script_value_ref; +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/text.cc b/bridge/core/api/text.cc new file mode 100644 index 0000000000..4bdb34d678 --- /dev/null +++ b/bridge/core/api/text.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/text.h" +#include "core/dom/character_data.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/api/window.cc b/bridge/core/api/window.cc new file mode 100644 index 0000000000..de6dd8ba7d --- /dev/null +++ b/bridge/core/api/window.cc @@ -0,0 +1,8 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/window.h" +#include "core/dom/events/event_target.h" + +namespace webf {} // namespace webf \ No newline at end of file diff --git a/bridge/core/binding_object.cc b/bridge/core/binding_object.cc index b138e01fa5..3d32da15d3 100644 --- a/bridge/core/binding_object.cc +++ b/bridge/core/binding_object.cc @@ -19,7 +19,7 @@ namespace webf { static void ReturnEventResultToDart(Dart_Handle persistent_handle, NativeValue* result, DartInvokeResultCallback result_callback) { - Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + const Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); result_callback(handle, result); Dart_DeletePersistentHandle_DL(persistent_handle); } @@ -39,20 +39,20 @@ static void HandleCallFromDartSideWrapper(NativeBindingObject* binding_object, auto is_dedicated = binding_object->binding_target_->GetExecutingContext()->isDedicated(); auto context_id = binding_object->binding_target_->contextId(); - dart_isolate->dispatcher()->PostToJs(is_dedicated, context_id, NativeBindingObject::HandleCallFromDartSide, - dart_isolate, binding_object, profile_id, method, argc, argv, persistent_handle, - result_callback); + dart_isolate->dispatcher()->PostToJs(is_dedicated, static_cast(context_id), + NativeBindingObject::HandleCallFromDartSide, dart_isolate, binding_object, + profile_id, method, argc, argv, persistent_handle, result_callback); } NativeBindingObject::NativeBindingObject(BindingObject* target) : binding_target_(target), invoke_binding_methods_from_dart(HandleCallFromDartSideWrapper) {} -void NativeBindingObject::HandleCallFromDartSide(DartIsolateContext* dart_isolate_context, - NativeBindingObject* binding_object, +void NativeBindingObject::HandleCallFromDartSide(const DartIsolateContext* dart_isolate_context, + const NativeBindingObject* binding_object, int64_t profile_id, - NativeValue* native_method, + const NativeValue* native_method, int32_t argc, - NativeValue* argv, + const NativeValue* argv, Dart_PersistentHandle dart_object, DartInvokeResultCallback result_callback) { if (binding_object->disposed_) @@ -60,10 +60,10 @@ void NativeBindingObject::HandleCallFromDartSide(DartIsolateContext* dart_isolat dart_isolate_context->profiler()->StartTrackEvaluation(profile_id); - AtomicString method = AtomicString( - binding_object->binding_target_->ctx(), - std::unique_ptr(reinterpret_cast(native_method->u.ptr))); - NativeValue result = binding_object->binding_target_->HandleCallFromDartSide(method, argc, argv, dart_object); + const AtomicString method = + AtomicString(binding_object->binding_target_->ctx(), + std::unique_ptr(static_cast(native_method->u.ptr))); + const NativeValue result = binding_object->binding_target_->HandleCallFromDartSide(method, argc, argv, dart_object); auto* return_value = new NativeValue(); std::memcpy(return_value, &result, sizeof(NativeValue)); diff --git a/bridge/core/binding_object.h b/bridge/core/binding_object.h index ec0d328cd1..693a2c2627 100644 --- a/bridge/core/binding_object.h +++ b/bridge/core/binding_object.h @@ -46,12 +46,12 @@ struct NativeBindingObject : public DartReadable { NativeBindingObject() = delete; explicit NativeBindingObject(BindingObject* target); - static void HandleCallFromDartSide(DartIsolateContext* dart_isolate_context, - NativeBindingObject* binding_object, + static void HandleCallFromDartSide(const DartIsolateContext* dart_isolate_context, + const NativeBindingObject* binding_object, int64_t profile_id, - NativeValue* method, + const NativeValue* method, int32_t argc, - NativeValue* argv, + const NativeValue* argv, Dart_PersistentHandle dart_object, DartInvokeResultCallback result_callback); diff --git a/bridge/core/dart_isolate_context.cc b/bridge/core/dart_isolate_context.cc index 73dee33eae..3787b1e533 100644 --- a/bridge/core/dart_isolate_context.cc +++ b/bridge/core/dart_isolate_context.cc @@ -85,8 +85,7 @@ void DartIsolateContext::InitializeJSRuntime() { } void DartIsolateContext::FinalizeJSRuntime() { - if (running_dart_isolates > 0 || - runtime_ == nullptr) { + if (running_dart_isolates > 0 || runtime_ == nullptr) { return; } diff --git a/bridge/core/dart_methods.cc b/bridge/core/dart_methods.cc index 1a8c8e0245..cce625e2de 100644 --- a/bridge/core/dart_methods.cc +++ b/bridge/core/dart_methods.cc @@ -31,10 +31,13 @@ DartMethodPointer::DartMethodPointer(DartIsolateContext* dart_isolate_context, to_blob_ = reinterpret_cast(dart_methods[i++]); flush_ui_command_ = reinterpret_cast(dart_methods[i++]); create_binding_object_ = reinterpret_cast(dart_methods[i++]); + load_native_library_ = reinterpret_cast(dart_methods[i++]); get_widget_element_shape_ = reinterpret_cast(dart_methods[i++]); on_js_error_ = reinterpret_cast(dart_methods[i++]); on_js_log_ = reinterpret_cast(dart_methods[i++]); + WEBF_LOG(VERBOSE) << "2 on Js" << load_native_library_; + assert_m(i == dart_methods_length, "Dart native methods count is not equal with C++ side method registrations."); } @@ -216,6 +219,24 @@ void DartMethodPointer::createBindingObject(bool is_dedicated, #endif } +void DartMethodPointer::loadNativeLibrary(bool is_dedicated, + double context_id, + webf::SharedNativeString* lib_name, + void* initialize_data, + void* import_data, + LoadNativeLibraryCallback callback) { +#if ENABLE_LOG + WEBF_LOG(INFO) << "[Dispatcher] DartMethodPointer::loadNativeLibrary SYNC call START"; +#endif + + dart_isolate_context_->dispatcher()->PostToDart(is_dedicated, load_native_library_, context_id, lib_name, + initialize_data, import_data, callback); + +#if ENABLE_LOG + WEBF_LOG(INFO) << "[Dispatcher] DartMethodPointer::loadNativeLibrary SYNC call END"; +#endif +} + bool DartMethodPointer::getWidgetElementShape(bool is_dedicated, double context_id, void* native_binding_object, diff --git a/bridge/core/dart_methods.h b/bridge/core/dart_methods.h index bd11aeb4a3..a99cfad4f7 100644 --- a/bridge/core/dart_methods.h +++ b/bridge/core/dart_methods.h @@ -14,6 +14,7 @@ #include "foundation/native_string.h" #include "foundation/native_value.h" #include "include/dart_api.h" +#include "plugin_api/executing_context.h" #if defined(_WIN32) #define WEBF_EXPORT_C extern "C" __declspec(dllexport) @@ -35,6 +36,12 @@ using AsyncModuleCallback = NativeValue* (*)(void* callback_context, Dart_PersistentHandle persistent_handle, InvokeModuleResultCallback result_callback); +using PluginLibraryEntryPoint = void* (*)(WebFValue handle_context); +using LoadNativeLibraryCallback = void (*)(PluginLibraryEntryPoint entry_point, + void* initialize_data, + double context_id, + void* imported_data); + using AsyncBlobCallback = void (*)(void* callback_context, double context_id, char* error, uint8_t* bytes, int32_t length); typedef NativeValue* (*InvokeModule)(void* callback_context, @@ -72,6 +79,11 @@ typedef void (*OnJSLog)(double context_id, int32_t level, const char*); typedef void (*FlushUICommand)(double context_id, void* native_binding_object); typedef void ( *CreateBindingObject)(double context_id, void* native_binding_object, int32_t type, void* args, int32_t argc); +typedef void (*LoadNativeLibrary)(double context_id, + SharedNativeString* lib_name, + void* initialize_data, + void* import_data, + LoadNativeLibraryCallback callback); typedef int8_t (*GetWidgetElementShape)(double context_id, void* native_binding_object, NativeValue* value); using MatchImageSnapshotCallback = void (*)(void* callback_context, double context_id, int8_t, char* errmsg); @@ -179,6 +191,12 @@ class DartMethodPointer { int32_t type, void* args, int32_t argc); + void loadNativeLibrary(bool is_dedicated, + double context_id, + SharedNativeString* lib_name, + void* initialize_data, + void* import_data, + LoadNativeLibraryCallback callback); bool getWidgetElementShape(bool is_dedicated, double context_id, void* native_binding_object, NativeValue* value); void onJSError(bool is_dedicated, double context_id, const char*); @@ -230,6 +248,7 @@ class DartMethodPointer { ToBlob to_blob_{nullptr}; FlushUICommand flush_ui_command_{nullptr}; CreateBindingObject create_binding_object_{nullptr}; + LoadNativeLibrary load_native_library_{nullptr}; GetWidgetElementShape get_widget_element_shape_{nullptr}; OnJSError on_js_error_{nullptr}; OnJSLog on_js_log_{nullptr}; diff --git a/bridge/core/dom/character_data.cc b/bridge/core/dom/character_data.cc index 6d30dcc005..7a518d073a 100644 --- a/bridge/core/dom/character_data.cc +++ b/bridge/core/dom/character_data.cc @@ -48,4 +48,9 @@ CharacterData::CharacterData(TreeScope& tree_scope, const AtomicString& text, No assert(type == kCreateOther || type == kCreateText); } +const CharacterDataPublicMethods* CharacterData::characterDataPublicMethods() { + static CharacterDataPublicMethods character_data_public_methods; + return &character_data_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/character_data.h b/bridge/core/dom/character_data.h index e8b373f613..c5de4f129c 100644 --- a/bridge/core/dom/character_data.h +++ b/bridge/core/dom/character_data.h @@ -7,6 +7,7 @@ #define BRIDGE_CHARACTER_DATA_H #include "node.h" +#include "plugin_api/character_data.h" namespace webf { @@ -16,6 +17,8 @@ class CharacterData : public Node { DEFINE_WRAPPERTYPEINFO(); public: + // static CharacterDataRustMethods* rustMethodPointer(); + const AtomicString& data() const { return data_; } int64_t length() const { return data_.length(); }; void setData(const AtomicString& data, ExceptionState& exception_state); @@ -26,6 +29,8 @@ class CharacterData : public Node { bool IsCharacterDataNode() const override; void setNodeValue(const AtomicString&, ExceptionState&) override; + const CharacterDataPublicMethods* characterDataPublicMethods(); + protected: CharacterData(TreeScope& tree_scope, const AtomicString& text, ConstructionType type); diff --git a/bridge/core/dom/comment.cc b/bridge/core/dom/comment.cc index 43eb429947..5b09f201c1 100644 --- a/bridge/core/dom/comment.cc +++ b/bridge/core/dom/comment.cc @@ -37,4 +37,9 @@ Node* Comment::Clone(Document& factory, CloneChildrenFlag flag) const { return copy; } +const CommentPublicMethods* Comment::commentPublicMethods() { + static CommentPublicMethods comment_public_methods; + return &comment_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/comment.h b/bridge/core/dom/comment.h index 5b19e94269..3068c71e6c 100644 --- a/bridge/core/dom/comment.h +++ b/bridge/core/dom/comment.h @@ -6,6 +6,7 @@ #define BRIDGE_COMMENT_H #include "character_data.h" +#include "plugin_api/comment.h" namespace webf { @@ -20,6 +21,8 @@ class Comment : public CharacterData { NodeType nodeType() const override; + const CommentPublicMethods* commentPublicMethods(); + private: std::string nodeName() const override; Node* Clone(Document&, CloneChildrenFlag) const override; @@ -28,6 +31,9 @@ class Comment : public CharacterData { template <> struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsOtherNode(); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsOtherNode(); + } }; } // namespace webf diff --git a/bridge/core/dom/container_node.cc b/bridge/core/dom/container_node.cc index d2711e8466..6cee0b81f1 100644 --- a/bridge/core/dom/container_node.cc +++ b/bridge/core/dom/container_node.cc @@ -573,4 +573,9 @@ void ContainerNode::Trace(GCVisitor* visitor) const { Node::Trace(visitor); } +const ContainerNodePublicMethods* ContainerNode::containerNodePublicMethods() { + static ContainerNodePublicMethods container_node_public_methods; + return &container_node_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/container_node.h b/bridge/core/dom/container_node.h index 136d2a77c3..9d78080149 100644 --- a/bridge/core/dom/container_node.h +++ b/bridge/core/dom/container_node.h @@ -11,6 +11,7 @@ #include "bindings/qjs/heap_vector.h" #include "core/html/collection_type.h" #include "node.h" +#include "plugin_api/container_node.h" namespace webf { @@ -151,6 +152,7 @@ class ContainerNode : public Node { Collection* EnsureCachedCollection(CollectionType); void Trace(GCVisitor* visitor) const override; + const ContainerNodePublicMethods* containerNodePublicMethods(); protected: ContainerNode(TreeScope* tree_scope, ConstructionType = kCreateContainer); diff --git a/bridge/core/dom/document.cc b/bridge/core/dom/document.cc index 3e62884e6f..2c646dc4e7 100644 --- a/bridge/core/dom/document.cc +++ b/bridge/core/dom/document.cc @@ -413,4 +413,9 @@ void Document::Trace(GCVisitor* visitor) const { ContainerNode::Trace(visitor); } +const DocumentPublicMethods* Document::documentPublicMethods() { + static DocumentPublicMethods document_public_methods; + return &document_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/document.h b/bridge/core/dom/document.h index 88c5b0cfa2..a7654240e7 100644 --- a/bridge/core/dom/document.h +++ b/bridge/core/dom/document.h @@ -8,6 +8,7 @@ #include "bindings/qjs/cppgc/local_handle.h" #include "container_node.h" #include "event_type_names.h" +#include "plugin_api/document.h" #include "scripted_animation_controller.h" #include "tree_scope.h" @@ -126,6 +127,7 @@ class Document : public ContainerNode, public TreeScope { std::shared_ptr GetWindowAttributeEventListener(const AtomicString& event_type); void Trace(GCVisitor* visitor) const override; + const DocumentPublicMethods* documentPublicMethods(); private: int node_count_{0}; @@ -136,6 +138,9 @@ class Document : public ContainerNode, public TreeScope { template <> struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsDocumentNode(); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsDocumentNode(); + } }; } // namespace webf diff --git a/bridge/core/dom/document_fragment.cc b/bridge/core/dom/document_fragment.cc index fd98afb54e..8c0d7e0902 100644 --- a/bridge/core/dom/document_fragment.cc +++ b/bridge/core/dom/document_fragment.cc @@ -53,4 +53,9 @@ bool DocumentFragment::ChildTypeAllowed(NodeType type) const { } } +const DocumentFragmentPublicMethods* DocumentFragment::documentFragmentPublicMethods() { + static DocumentFragmentPublicMethods document_public_methods; + return &document_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/document_fragment.h b/bridge/core/dom/document_fragment.h index 8d7d7649c8..3e75bb7f74 100644 --- a/bridge/core/dom/document_fragment.h +++ b/bridge/core/dom/document_fragment.h @@ -26,6 +26,8 @@ class DocumentFragment : public ContainerNode { AtomicString nodeValue() const override; + const DocumentFragmentPublicMethods* documentFragmentPublicMethods(); + protected: std::string nodeName() const final; @@ -38,6 +40,9 @@ class DocumentFragment : public ContainerNode { template <> struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsDocumentFragment(); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsDocumentFragment(); + } }; } // namespace webf diff --git a/bridge/core/dom/dom_string_map.cc b/bridge/core/dom/dom_string_map.cc index 1b3ec3a293..552ee4116f 100644 --- a/bridge/core/dom/dom_string_map.cc +++ b/bridge/core/dom/dom_string_map.cc @@ -23,7 +23,7 @@ static bool IsValidAttributeName(const AtomicString& name) { if (!startsWith((const char*)name.Character8(), "data-")) return false; - unsigned length = name.length(); + const int64_t length = name.length(); for (unsigned i = 5; i < length; ++i) { if (IsASCIIUpper(name.Character8()[i])) return false; @@ -33,7 +33,7 @@ static bool IsValidAttributeName(const AtomicString& name) { } static bool IsValidPropertyName(const AtomicString& name) { - unsigned length = name.length(); + const int64_t length = name.length(); for (unsigned i = 0; i < length; ++i) { if (name.Character8()[i] == '-' && (i + 1 < length) && IsASCIILower(name.Character8()[i + 1])) return false; diff --git a/bridge/core/dom/dom_token_list.h b/bridge/core/dom/dom_token_list.h index 9f48aa8a73..6d28d06592 100644 --- a/bridge/core/dom/dom_token_list.h +++ b/bridge/core/dom/dom_token_list.h @@ -23,7 +23,7 @@ class DOMTokenList : public ScriptWrappable { explicit DOMTokenList(Element* element, const AtomicString& attr); DOMTokenList() = delete; - unsigned length() const { return token_set_.size(); } + size_t length() const { return token_set_.size(); } const AtomicString item(unsigned index, ExceptionState& exception_state) const; bool contains(const AtomicString&, ExceptionState&) const; void add(const std::vector&, ExceptionState&); diff --git a/bridge/core/dom/element.cc b/bridge/core/dom/element.cc index 99a144e4be..a54d131732 100644 --- a/bridge/core/dom/element.cc +++ b/bridge/core/dom/element.cc @@ -20,6 +20,7 @@ #include "foundation/native_value_converter.h" #include "html_element_type_helper.h" #include "mutation_observer_interest_group.h" +#include "plugin_api/element.h" #include "qjs_element.h" #include "text.h" @@ -343,6 +344,11 @@ void Element::Trace(GCVisitor* visitor) const { ContainerNode::Trace(visitor); } +const ElementPublicMethods* Element::elementPublicMethods() { + static ElementPublicMethods element_public_methods; + return &element_public_methods; +} + // https://dom.spec.whatwg.org/#concept-element-qualified-name const AtomicString Element::getUppercasedQualifiedName() const { auto name = getQualifiedName(); diff --git a/bridge/core/dom/element.h b/bridge/core/dom/element.h index 2be3d5fbab..74d5833957 100644 --- a/bridge/core/dom/element.h +++ b/bridge/core/dom/element.h @@ -13,6 +13,7 @@ #include "legacy/bounding_client_rect.h" #include "legacy/element_attributes.h" #include "parent_node.h" +#include "plugin_api/element.h" #include "qjs_scroll_to_options.h" namespace webf { @@ -143,6 +144,7 @@ class Element : public ContainerNode { virtual bool IsWidgetElement() const; void Trace(GCVisitor* visitor) const override; + const ElementPublicMethods* elementPublicMethods(); protected: void SetAttributeInternal(const AtomicString&, diff --git a/bridge/core/dom/events/custom_event.cc b/bridge/core/dom/events/custom_event.cc index 52a9bd345a..19825f3bab 100644 --- a/bridge/core/dom/events/custom_event.cc +++ b/bridge/core/dom/events/custom_event.cc @@ -4,6 +4,7 @@ */ #include "custom_event.h" #include "bindings/qjs/cppgc/gc_visitor.h" +#include "core/native/script_value_ref.h" #include "native_value_converter.h" namespace webf { @@ -65,6 +66,17 @@ void CustomEvent::initCustomEvent(const AtomicString& type, } } +void CustomEvent::initCustomEvent(const webf::AtomicString& type, + bool can_bubble, + bool cancelable, + const webf::ScriptValueRef* script_value_ref, + webf::ExceptionState& exception_state) { + initEvent(type, can_bubble, cancelable, exception_state); + if (!IsBeingDispatched() && !(script_value_ref->script_value).IsEmpty()) { + detail_ = script_value_ref->script_value; + } +} + bool CustomEvent::IsCustomEvent() const { return true; } diff --git a/bridge/core/dom/events/custom_event.h b/bridge/core/dom/events/custom_event.h index 964663b49b..feb057d446 100644 --- a/bridge/core/dom/events/custom_event.h +++ b/bridge/core/dom/events/custom_event.h @@ -48,6 +48,11 @@ class CustomEvent final : public Event { bool cancelable, const ScriptValue& detail, ExceptionState& exception_state); + void initCustomEvent(const AtomicString& type, + bool can_bubble, + bool cancelable, + const ScriptValueRef* script_value_ref, + ExceptionState& exception_state); bool IsCustomEvent() const override; diff --git a/bridge/core/dom/events/event.cc b/bridge/core/dom/events/event.cc index 498f2b9fcc..65fecfac77 100644 --- a/bridge/core/dom/events/event.cc +++ b/bridge/core/dom/events/event.cc @@ -365,4 +365,8 @@ void Event::Trace(GCVisitor* visitor) const { } } +const EventPublicMethods* Event::eventPublicMethods() { + return &event_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/events/event.h b/bridge/core/dom/events/event.h index 27640cb4b9..f7582856db 100644 --- a/bridge/core/dom/events/event.h +++ b/bridge/core/dom/events/event.h @@ -236,6 +236,8 @@ class Event : public ScriptWrappable { void Trace(GCVisitor* visitor) const override; + const EventPublicMethods* eventPublicMethods(); + protected: PassiveMode HandlingPassive() const { return handling_passive_; } @@ -266,6 +268,7 @@ class Event : public ScriptWrappable { Member target_; Member current_target_; std::vector customized_event_props_; + EventPublicMethods event_public_methods; friend void set_event_prop(JSContext* ctx, EventProp* prop, Event* event, diff --git a/bridge/core/dom/events/event_listener.h b/bridge/core/dom/events/event_listener.h index be4db43a8e..19d3ba4a7a 100644 --- a/bridge/core/dom/events/event_listener.h +++ b/bridge/core/dom/events/event_listener.h @@ -37,6 +37,8 @@ class EventListener { // Returns true if this implements IDL EventHandler family. virtual bool IsEventHandler() const { return false; } + virtual bool IsPublicPluginEventHandler() const { return false; } + // Returns true if this implements IDL EventHandler family and the value is // a content attribute (or compiled from a content attribute). virtual bool IsEventHandlerForContentAttribute() const { return false; } @@ -51,7 +53,7 @@ class EventListener { virtual void Trace(GCVisitor* visitor) const = 0; - private: + protected: EventListener() = default; friend JSBasedEventListener; diff --git a/bridge/core/dom/events/event_target.cc b/bridge/core/dom/events/event_target.cc index 1636b45b2d..7c77a5037f 100644 --- a/bridge/core/dom/events/event_target.cc +++ b/bridge/core/dom/events/event_target.cc @@ -2,11 +2,12 @@ * Copyright (C) 2019-2022 The Kraken authors. All rights reserved. * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#include "event_target.h" +#include "plugin_api/event_target.h" #include #include "binding_call_methods.h" #include "bindings/qjs/converter_impl.h" #include "event_factory.h" +#include "event_target.h" #include "include/dart_api.h" #include "native_value_converter.h" #include "qjs_add_event_listener_options.h" @@ -78,7 +79,8 @@ bool EventTarget::addEventListener(const AtomicString& event_type, const std::shared_ptr& event_listener, const std::shared_ptr& options, ExceptionState& exception_state) { - if (event_listener == nullptr) return false; + if (event_listener == nullptr) + return false; std::shared_ptr event_listener_options; if (options == nullptr) { event_listener_options = AddEventListenerOptions::Create(); @@ -101,6 +103,13 @@ bool EventTarget::addEventListener(const AtomicString& event_type, return AddEventListenerInternal(event_type, event_listener, options); } +bool EventTarget::addEventListener(const webf::AtomicString& event_type, + const std::shared_ptr& event_listener, + const std::shared_ptr& options, + ExceptionState& exception_state) { + return AddEventListenerInternal(event_type, event_listener, options); +} + bool EventTarget::removeEventListener(const AtomicString& event_type, const std::shared_ptr& event_listener, ExceptionState& exception_state) { @@ -151,6 +160,8 @@ bool EventTarget::dispatchEvent(Event* event, ExceptionState& exception_state) { if (!GetExecutingContext()) return false; + MemberMutationScope scope{GetExecutingContext()}; + event->SetTrusted(false); // Return whether the event was cancelled or not to JS not that it @@ -247,6 +258,11 @@ bool EventTarget::IsEventTarget() const { return true; } +const EventTargetPublicMethods* EventTarget::eventTargetPublicMethods() { + static EventTargetPublicMethods event_target_public_methods; + return &event_target_public_methods; +} + void EventTarget::Trace(GCVisitor* visitor) const { ScriptWrappable::Trace(visitor); BindingObject::Trace(visitor); diff --git a/bridge/core/dom/events/event_target.h b/bridge/core/dom/events/event_target.h index d473640389..79d04ac3e5 100644 --- a/bridge/core/dom/events/event_target.h +++ b/bridge/core/dom/events/event_target.h @@ -13,6 +13,7 @@ #include "event_listener_map.h" #include "foundation/logging.h" #include "foundation/native_string.h" +#include "plugin_api/event_target.h" #include "qjs_add_event_listener_options.h" #include "qjs_unionadd_event_listener_options_boolean.h" #include "qjs_unionevent_listener_options_boolean.h" @@ -105,6 +106,10 @@ class EventTarget : public BindingObject { bool addEventListener(const AtomicString& event_type, const std::shared_ptr& event_listener, ExceptionState& exception_state); + bool addEventListener(const AtomicString& event_type, + const std::shared_ptr& event_listener, + const std::shared_ptr& options, + ExceptionState& exception_state); bool removeEventListener(const AtomicString& event_type, const std::shared_ptr& event_listener, ExceptionState& exception_state); @@ -135,6 +140,8 @@ class EventTarget : public BindingObject { virtual bool IsNode() const { return false; } bool IsEventTarget() const override; + const EventTargetPublicMethods* eventTargetPublicMethods(); + NativeValue HandleCallFromDartSide(const AtomicString& method, int32_t argc, const NativeValue* argv, diff --git a/bridge/core/dom/node.cc b/bridge/core/dom/node.cc index 538a919cd2..662edaff70 100644 --- a/bridge/core/dom/node.cc +++ b/bridge/core/dom/node.cc @@ -29,7 +29,7 @@ * Copyright (C) 2022-present The WebF authors. All rights reserved. */ -#include "node.h" +#include "plugin_api/node.h" #include #include "character_data.h" #include "child_list_mutation_scope.h" @@ -39,6 +39,7 @@ #include "document_fragment.h" #include "element.h" #include "empty_node_list.h" +#include "node.h" #include "node_data.h" #include "node_traversal.h" #include "qjs_node.h" @@ -713,4 +714,9 @@ void Node::Trace(GCVisitor* visitor) const { EventTarget::Trace(visitor); } +const NodePublicMethods* Node::nodePublicMethods() { + static NodePublicMethods node_public_methods; + return &node_public_methods; +} + } // namespace webf diff --git a/bridge/core/dom/node.h b/bridge/core/dom/node.h index 2ae6a735b5..7fc5076959 100644 --- a/bridge/core/dom/node.h +++ b/bridge/core/dom/node.h @@ -14,6 +14,7 @@ #include "mutation_observer.h" #include "mutation_observer_registration.h" #include "node_data.h" +#include "plugin_api/node.h" #include "qjs_union_dom_stringnode.h" #include "tree_scope.h" @@ -259,6 +260,7 @@ class Node : public EventTarget { const MutationObserverRegistrationSet* TransientMutationObserverRegistry(); void Trace(GCVisitor*) const override; + const NodePublicMethods* nodePublicMethods(); private: enum NodeFlags : uint32_t { diff --git a/bridge/core/dom/text.cc b/bridge/core/dom/text.cc index c9ff05f943..d6d4037e7c 100644 --- a/bridge/core/dom/text.cc +++ b/bridge/core/dom/text.cc @@ -24,6 +24,11 @@ Node::NodeType Text::nodeType() const { return Node::kTextNode; } +const TextNodePublicMethods* Text::textNodePublicMethods() { + static TextNodePublicMethods text_node_public_methods; + return &text_node_public_methods; +} + std::string Text::nodeName() const { return "#text"; } diff --git a/bridge/core/dom/text.h b/bridge/core/dom/text.h index 2d9ef22bcf..0f3d8f9bc9 100644 --- a/bridge/core/dom/text.h +++ b/bridge/core/dom/text.h @@ -7,6 +7,7 @@ #define BRIDGE_CORE_DOM_TEXT_H_ #include "character_data.h" +#include "plugin_api/text.h" namespace webf { @@ -26,6 +27,7 @@ class Text : public CharacterData { } NodeType nodeType() const override; + const TextNodePublicMethods* textNodePublicMethods(); private: std::string nodeName() const override; @@ -36,6 +38,9 @@ template <> struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsTextNode(); }; static bool AllowFrom(const CharacterData& character_data) { return character_data.IsTextNode(); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsTextNode(); + } }; } // namespace webf diff --git a/bridge/core/events/hybrid_router_change_event.h b/bridge/core/events/hybrid_router_change_event.h index f88a47e06e..8d7c7a5c21 100644 --- a/bridge/core/events/hybrid_router_change_event.h +++ b/bridge/core/events/hybrid_router_change_event.h @@ -21,18 +21,22 @@ class HybridRouterChangeEvent : public Event { static HybridRouterChangeEvent* Create(ExecutingContext* context, ExceptionState& exception_state); static HybridRouterChangeEvent* Create(ExecutingContext* context, - const AtomicString& type, - const std::shared_ptr& initializer, - ExceptionState& exception_state); + const AtomicString& type, + const std::shared_ptr& initializer, + ExceptionState& exception_state); - explicit HybridRouterChangeEvent(ExecutingContext* context, const AtomicString& type, ExceptionState& exception_state); + explicit HybridRouterChangeEvent(ExecutingContext* context, + const AtomicString& type, + ExceptionState& exception_state); explicit HybridRouterChangeEvent(ExecutingContext* context, - const AtomicString& type, - const std::shared_ptr& initializer, - ExceptionState& exception_state); + const AtomicString& type, + const std::shared_ptr& initializer, + ExceptionState& exception_state); - explicit HybridRouterChangeEvent(ExecutingContext* context, const AtomicString& type, NativeHybridRouterChangeEvent* native_ui_event); + explicit HybridRouterChangeEvent(ExecutingContext* context, + const AtomicString& type, + NativeHybridRouterChangeEvent* native_ui_event); ScriptValue state() const; AtomicString kind() const; diff --git a/bridge/core/executing_context.cc b/bridge/core/executing_context.cc index 14c4aff2a1..fedf4520dd 100644 --- a/bridge/core/executing_context.cc +++ b/bridge/core/executing_context.cc @@ -34,8 +34,9 @@ ExecutingContext::ExecutingContext(DartIsolateContext* dart_isolate_context, void* owner) : dart_isolate_context_(dart_isolate_context), context_id_(context_id), - handler_(std::move(handler)), + dart_error_report_handler_(std::move(handler)), owner_(owner), + public_method_ptr_(std::make_unique()), is_dedicated_(is_dedicated), unique_id_(context_unique_id++), is_context_valid_(true) { @@ -85,6 +86,7 @@ ExecutingContext::ExecutingContext(DartIsolateContext* dart_isolate_context, // Install performance InstallPerformance(); + InstallNativeLoader(); dart_isolate_context->profiler()->FinishTrackSteps(); dart_isolate_context->profiler()->StartTrackSteps("ExecutingContext::initWebFPolyFill"); @@ -277,6 +279,18 @@ bool ExecutingContext::HandleException(ExceptionState& exception_state) { return true; } +bool ExecutingContext ::HandleException(webf::ExceptionState& exception_state, + char** rust_error_msg, + uint32_t* rust_errmsg_len) { + if (exception_state.HasException()) { + JSValue error = JS_GetException(ctx()); + ReportError(error, rust_error_msg, rust_errmsg_len); + JS_FreeValue(ctx(), error); + return false; + } + return true; +} + JSValue ExecutingContext::Global() { return global_object_; } @@ -286,37 +300,50 @@ JSContext* ExecutingContext::ctx() { return script_state_.ctx(); } -void ExecutingContext::ReportError(JSValueConst error) { +void ExecutingContext::ReportError(JSValue error) { + ReportError(error, nullptr, nullptr); +} + +void ExecutingContext::ReportError(JSValueConst error, char** rust_errmsg, uint32_t* rust_errmsg_length) { JSContext* ctx = script_state_.ctx(); if (!JS_IsError(ctx, error)) return; - JSValue messageValue = JS_GetPropertyStr(ctx, error, "message"); - JSValue errorTypeValue = JS_GetPropertyStr(ctx, error, "name"); - const char* title = JS_ToCString(ctx, messageValue); - const char* type = JS_ToCString(ctx, errorTypeValue); + JSValue message_value = JS_GetPropertyStr(ctx, error, "message"); + JSValue error_type_value = JS_GetPropertyStr(ctx, error, "name"); + const char* title = JS_ToCString(ctx, message_value); + const char* type = JS_ToCString(ctx, error_type_value); const char* stack = nullptr; - JSValue stackValue = JS_GetPropertyStr(ctx, error, "stack"); - if (!JS_IsUndefined(stackValue)) { - stack = JS_ToCString(ctx, stackValue); + JSValue stack_value = JS_GetPropertyStr(ctx, error, "stack"); + if (!JS_IsUndefined(stack_value)) { + stack = JS_ToCString(ctx, stack_value); } - uint32_t messageLength = strlen(type) + strlen(title); + uint32_t message_length = strlen(type) + strlen(title); + char* message; if (stack != nullptr) { - messageLength += 4 + strlen(stack); - char* message = (char*)dart_malloc(messageLength * sizeof(char)); - snprintf(message, messageLength, "%s: %s\n%s", type, title, stack); - handler_(this, message); + message_length += 4 + strlen(stack); + message = (char*)dart_malloc(message_length * sizeof(char)); + snprintf(message, message_length, "%s: %s\n%s", type, title, stack); + } else { + message_length += 3; + message = (char*)dart_malloc(message_length * sizeof(char)); + snprintf(message, message_length, "%s: %s", type, title); + } + + // Report errmsg to rust side + if (rust_errmsg != nullptr && rust_errmsg_length != nullptr) { + *rust_errmsg = (char*)malloc(sizeof(char) * message_length); + *rust_errmsg_length = message_length; + memcpy(*rust_errmsg, message, sizeof(char) * message_length); } else { - messageLength += 3; - char* message = (char*)dart_malloc(messageLength * sizeof(char)); - snprintf(message, messageLength, "%s: %s", type, title); - handler_(this, message); + // Report errmsg to dart side + dart_error_report_handler_(this, message); } - JS_FreeValue(ctx, errorTypeValue); - JS_FreeValue(ctx, messageValue); - JS_FreeValue(ctx, stackValue); + JS_FreeValue(ctx, error_type_value); + JS_FreeValue(ctx, message_value); + JS_FreeValue(ctx, stack_value); JS_FreeCString(ctx, title); JS_FreeCString(ctx, stack); JS_FreeCString(ctx, type); @@ -595,6 +622,12 @@ void ExecutingContext::InstallPerformance() { DefineGlobalProperty("performance", performance_->ToQuickJS()); } +void ExecutingContext::InstallNativeLoader() { + MemberMutationScope scope{this}; + native_loader_ = MakeGarbageCollected(this); + DefineGlobalProperty("nativeLoader", native_loader_->ToQuickJS()); +} + void ExecutingContext::InstallGlobal() { MemberMutationScope mutation_scope{this}; window_ = MakeGarbageCollected(this); diff --git a/bridge/core/executing_context.h b/bridge/core/executing_context.h index c87ca8f58f..dc6c97c7eb 100644 --- a/bridge/core/executing_context.h +++ b/bridge/core/executing_context.h @@ -16,12 +16,15 @@ #include #include #include +#include #include #include "bindings/qjs/binding_initializer.h" #include "bindings/qjs/rejected_promises.h" #include "bindings/qjs/script_value.h" #include "foundation/macros.h" #include "foundation/ui_command_buffer.h" +#include "native/native_loader.h" +#include "plugin_api/executing_context.h" #include "dart_isolate_context.h" #include "dart_methods.h" @@ -93,7 +96,9 @@ class ExecutingContext { bool HandleException(JSValue* exc); bool HandleException(ScriptValue* exc); bool HandleException(ExceptionState& exception_state); + bool HandleException(ExceptionState& exception_state, char** rust_error_msg, uint32_t* rust_errmsg_len); void ReportError(JSValueConst error); + void ReportError(JSValueConst error, char** rust_errmsg, uint32_t* rust_errmsg_length); void DrainMicrotasks(); void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr); void DefineGlobalProperty(const char* prop, JSValueConst value); @@ -136,6 +141,7 @@ class ExecutingContext { assert(dart_isolate_context_->valid()); return dart_isolate_context_->dartMethodPtr(); } + FORCE_INLINE ExecutingContextWebFMethods* publicMethodPtr() const { return public_method_ptr_.get(); } FORCE_INLINE bool isDedicated() { return is_dedicated_; } FORCE_INLINE std::chrono::time_point timeOrigin() const { return time_origin_; } @@ -167,9 +173,9 @@ class ExecutingContext { void InstallDocument(); void InstallPerformance(); + void InstallNativeLoader(); void DrainPendingPromiseJobs(); - void EnsureEnqueueMicrotask(); static void promiseRejectTracker(JSContext* ctx, JSValueConst promise, @@ -195,11 +201,12 @@ class ExecutingContext { // ---------------------------------------------------------------------- std::atomic is_context_valid_{false}; double context_id_; - JSExceptionHandler handler_; + JSExceptionHandler dart_error_report_handler_; void* owner_; JSValue global_object_{JS_NULL}; Document* document_{nullptr}; Window* window_{nullptr}; + NativeLoader* native_loader_{nullptr}; Performance* performance_{nullptr}; DOMTimerCoordinator timers_; ModuleListenerContainer module_listener_container_; @@ -210,6 +217,9 @@ class ExecutingContext { MemberMutationScope* active_mutation_scope{nullptr}; std::unordered_set active_wrappers_; bool is_dedicated_; + + // Rust methods ptr should keep alive when ExecutingContext is disposing. + const std::unique_ptr public_method_ptr_ = nullptr; }; class ObjectProperty { diff --git a/bridge/core/executing_context_test.cc b/bridge/core/executing_context_test.cc index c508a6c316..54e6ec39e5 100644 --- a/bridge/core/executing_context_test.cc +++ b/bridge/core/executing_context_test.cc @@ -17,11 +17,11 @@ TEST(Context, isValid) { EXPECT_EQ(env->page()->executingContext()->IsCtxValid(), true); WEBF_LOG(VERBOSE) << env->page()->dartIsolateContext()->profiler()->ToJSON(); } - { - auto env = TEST_init(); - EXPECT_EQ(env->page()->executingContext()->IsContextValid(), true); - EXPECT_EQ(env->page()->executingContext()->IsCtxValid(), true); - } + // { + // auto env = TEST_init(); + // EXPECT_EQ(env->page()->executingContext()->IsContextValid(), true); + // EXPECT_EQ(env->page()->executingContext()->IsCtxValid(), true); + // } } TEST(Context, evalWithError) { diff --git a/bridge/core/frame/module_manager.h b/bridge/core/frame/module_manager.h index 229fd2f348..06d8e8ebb0 100644 --- a/bridge/core/frame/module_manager.h +++ b/bridge/core/frame/module_manager.h @@ -12,7 +12,8 @@ namespace webf { -struct ModuleContext { +class ModuleContext { + public: ModuleContext(ExecutingContext* context, const std::shared_ptr& callback) : context(context), callback(callback) {} ExecutingContext* context; diff --git a/bridge/core/frame/window.cc b/bridge/core/frame/window.cc index 5a83e1fa18..2696a30c18 100644 --- a/bridge/core/frame/window.cc +++ b/bridge/core/frame/window.cc @@ -38,8 +38,8 @@ AtomicString Window::btoa(const AtomicString& source, ExceptionState& exception_ std::string source_string = source.ToStdString(ctx()); - const size_t output_size = modp_b64_encode(reinterpret_cast(buffer.data()), - source_string.c_str(), source.length()); + const size_t output_size = + modp_b64_encode(reinterpret_cast(buffer.data()), source_string.c_str(), source.length()); const char* encode_str = buffer.data(); const size_t encode_str_len = strlen(encode_str); @@ -58,8 +58,8 @@ bool Base64DecodeRaw(JSContext* ctx, const AtomicString& in, std::vector(out.data()), - in_string.c_str(), in.length(), policy); + const size_t output_size = + modp_b64_decode(reinterpret_cast(out.data()), in_string.c_str(), in.length(), policy); if (output_size == MODP_B64_ERROR) return false; out.resize(output_size); @@ -270,6 +270,11 @@ void Window::Trace(GCVisitor* visitor) const { EventTargetWithInlineData::Trace(visitor); } +const WindowPublicMethods* Window::windowPublicMethods() { + static WindowPublicMethods window_public_methods; + return &window_public_methods; +} + JSValue Window::ToQuickJS() const { return JS_GetGlobalObject(ctx()); } diff --git a/bridge/core/frame/window.h b/bridge/core/frame/window.h index 391329c2a4..a2d5289870 100644 --- a/bridge/core/frame/window.h +++ b/bridge/core/frame/window.h @@ -9,6 +9,7 @@ #include "bindings/qjs/wrapper_type_info.h" #include "core/css/computed_css_style_declaration.h" #include "core/dom/events/event_target.h" +#include "plugin_api/window.h" #include "qjs_scroll_to_options.h" #include "screen.h" @@ -60,6 +61,7 @@ class Window : public EventTargetWithInlineData { bool IsWindowOrWorkerGlobalScope() const override; void Trace(GCVisitor* visitor) const override; + const WindowPublicMethods* windowPublicMethods(); // Override default ToQuickJS() to return Global object when access `window` property. JSValue ToQuickJS() const override; diff --git a/bridge/core/html/canvas/html_canvas_element.cc b/bridge/core/html/canvas/html_canvas_element.cc index 024bb741f2..70c6d267f9 100644 --- a/bridge/core/html/canvas/html_canvas_element.cc +++ b/bridge/core/html/canvas/html_canvas_element.cc @@ -41,4 +41,9 @@ void HTMLCanvasElement::Trace(GCVisitor* visitor) const { HTMLElement::Trace(visitor); } +const HTMLCanvasElementPublicMethods* HTMLCanvasElement::htmlCanvasElementPublicMethods() { + static HTMLCanvasElementPublicMethods html_canvas_element_public_methods; + return &html_canvas_element_public_methods; +} + } // namespace webf diff --git a/bridge/core/html/canvas/html_canvas_element.h b/bridge/core/html/canvas/html_canvas_element.h index 052e5951aa..03eda53002 100644 --- a/bridge/core/html/canvas/html_canvas_element.h +++ b/bridge/core/html/canvas/html_canvas_element.h @@ -8,6 +8,8 @@ #include #include "canvas_rendering_context.h" #include "core/html/html_element.h" +#include "html_names.h" +#include "plugin_api/html_canvas_element.h" namespace webf { @@ -22,6 +24,10 @@ class HTMLCanvasElement : public HTMLElement { void Trace(GCVisitor* visitor) const override; std::vector> running_context_2ds_; + + const HTMLCanvasElementPublicMethods* htmlCanvasElementPublicMethods(); + + private: }; } // namespace webf diff --git a/bridge/core/html/custom/widget_element.cc b/bridge/core/html/custom/widget_element.cc index 751ca84d0c..493b205000 100644 --- a/bridge/core/html/custom/widget_element.cc +++ b/bridge/core/html/custom/widget_element.cc @@ -42,6 +42,11 @@ void WidgetElement::NamedPropertyEnumerator(std::vector& names, Ex } } +// + +// const element = document.getElementById('custom-element'); +// element.dartFn(123, 23, 4); + ScriptValue WidgetElement::item(const AtomicString& key, ExceptionState& exception_state) { if (unimplemented_properties_.count(key) > 0) { return unimplemented_properties_[key]; diff --git a/bridge/core/html/html_element.h b/bridge/core/html/html_element.h index 13932279f1..652954a3d6 100644 --- a/bridge/core/html/html_element.h +++ b/bridge/core/html/html_element.h @@ -8,6 +8,7 @@ #include "core/dom/element.h" #include "core/dom/global_event_handlers.h" +#include "plugin_api/html_element.h" namespace webf { @@ -17,6 +18,13 @@ class HTMLElement : public Element { public: using ImplType = HTMLElement*; HTMLElement(const AtomicString& tag_name, Document* document, ConstructionType = kCreateHTMLElement); + + const HTMLElementPublicMethods* htmlElementPublicMethods() { + static HTMLElementPublicMethods html_element_public_methods; + return &html_element_public_methods; + } + + private: }; template @@ -32,6 +40,9 @@ inline bool IsElementOfType(const Node& node) { template <> struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsHTMLElement(); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsHTMLElement(); + } }; } // namespace webf diff --git a/bridge/core/html/html_image_element.cc b/bridge/core/html/html_image_element.cc index b7bfe6ddac..f2b8c5c17c 100644 --- a/bridge/core/html/html_image_element.cc +++ b/bridge/core/html/html_image_element.cc @@ -35,13 +35,14 @@ AtomicString HTMLImageElement::src() const { void HTMLImageElement::setSrc(const AtomicString& value, ExceptionState& exception_state) { SetBindingProperty(binding_call_methods::ksrc, NativeValueConverter::ToNativeValue(ctx(), value), exception_state); - if (!value.IsEmpty()) { + if (!value.IsEmpty() && !keep_alive) { KeepAlive(); + keep_alive = true; } } DispatchEventResult HTMLImageElement::FireEventListeners(Event& event, ExceptionState& exception_state) { - if (event.type() == event_type_names::kload || event.type() == event_type_names::kerror) { + if (keep_alive && (event.type() == event_type_names::kload || event.type() == event_type_names::kerror)) { ReleaseAlive(); } @@ -51,7 +52,7 @@ DispatchEventResult HTMLImageElement::FireEventListeners(Event& event, Exception DispatchEventResult HTMLImageElement::FireEventListeners(webf::Event& event, bool isCapture, webf::ExceptionState& exception_state) { - if (event.type() == event_type_names::kload || event.type() == event_type_names::kerror) { + if (keep_alive && (event.type() == event_type_names::kload || event.type() == event_type_names::kerror)) { ReleaseAlive(); } diff --git a/bridge/core/html/html_image_element.h b/bridge/core/html/html_image_element.h index ba4da17b15..ce64817430 100644 --- a/bridge/core/html/html_image_element.h +++ b/bridge/core/html/html_image_element.h @@ -6,6 +6,8 @@ #define BRIDGE_CORE_HTML_HTML_IMAGE_ELEMENT_H_ #include "html_element.h" +#include "html_names.h" +#include "plugin_api/html_image_element.h" namespace webf { @@ -23,7 +25,21 @@ class HTMLImageElement : public HTMLElement { ScriptPromise decode(ExceptionState& exception_state) const; + const HTMLImageElementPublicMethods* htmlImageElementPublicMethods() { + static HTMLImageElementPublicMethods html_image_element_public_methods; + return &html_image_element_public_methods; + } + private: + bool keep_alive = false; +}; + +template <> +struct DowncastTraits { + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsHTMLElement() && + To(event_target).tagName() == html_names::kimg; + } }; } // namespace webf diff --git a/bridge/core/native/native_loader.cc b/bridge/core/native/native_loader.cc new file mode 100644 index 0000000000..5312b6a55b --- /dev/null +++ b/bridge/core/native/native_loader.cc @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "native_loader.h" +#include "bindings/qjs/script_promise.h" +#include "bindings/qjs/script_promise_resolver.h" +#include "core/executing_context.h" +#include "plugin_api/webf_value.h" + +namespace webf { + +namespace { + +struct NativeLibraryLoadContext { + ExecutingContext* context{nullptr}; + std::shared_ptr promise_resolver{nullptr}; +}; + +} // namespace + +NativeLoader::NativeLoader(webf::ExecutingContext* context) : ScriptWrappable(context->ctx()) {} + +static void ExecuteNativeLibrary(PluginLibraryEntryPoint entry_point, + NativeLibraryLoadContext* native_library_load_context, + void* imported_data) { + // Encounter loading error. + if (entry_point == nullptr) { + ExceptionState exception_state; + auto* context = native_library_load_context->context; + exception_state.ThrowException(context->ctx(), ErrorType::InternalError, (const char*)(imported_data)); + JSValue exception_value = ExceptionState::CurrentException(context->ctx()); + native_library_load_context->promise_resolver->Reject(exception_value); + JS_FreeValue(context->ctx(), exception_value); + } else { + auto exec_status = new WebFValueStatus(); + auto entry_data = WebFValue{ + native_library_load_context->context, native_library_load_context->context->publicMethodPtr(), exec_status}; + WEBF_LOG(VERBOSE) << " entry_point: " << entry_point; + void* result = entry_point(entry_data); + WEBF_LOG(VERBOSE) << " result: " << result; + } + + delete native_library_load_context; + + WEBF_LOG(VERBOSE) << " EXEC LIB"; +} + +static void HandleNativeLibraryLoad(PluginLibraryEntryPoint entry_point, + void* initialize_data_ptr, + double context_id, + void* imported_data) { + auto* p_native_library_load_context = static_cast(initialize_data_ptr); + + auto* context = p_native_library_load_context->context; + + if (!context->IsContextValid()) + return; + + context->dartIsolateContext()->dispatcher()->PostToJs(context->isDedicated(), context_id, ExecuteNativeLibrary, + entry_point, p_native_library_load_context, imported_data); +} + +ScriptPromise NativeLoader::loadNativeLibrary(const AtomicString& lib_name, + const ScriptValue& import_object, + ExceptionState& exception_state) { + auto resolver = ScriptPromiseResolver::Create(GetExecutingContext()); + auto* context = GetExecutingContext(); + auto* p_native_library_load_context = new NativeLibraryLoadContext(); + + p_native_library_load_context->context = context; + p_native_library_load_context->promise_resolver = resolver; + + context->dartMethodPtr()->loadNativeLibrary(context->isDedicated(), context->contextId(), + lib_name.ToNativeString(ctx()).release(), p_native_library_load_context, + /* TODO */ nullptr, HandleNativeLibraryLoad); + + return resolver->Promise(); +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/core/native/native_loader.d.ts b/bridge/core/native/native_loader.d.ts new file mode 100644 index 0000000000..eca761ce32 --- /dev/null +++ b/bridge/core/native/native_loader.d.ts @@ -0,0 +1,4 @@ +interface NativeLoader { + new(): void; + loadNativeLibrary(libName: string, importObject: any): Promise; +} \ No newline at end of file diff --git a/bridge/core/native/native_loader.h b/bridge/core/native/native_loader.h new file mode 100644 index 0000000000..89b958ec6d --- /dev/null +++ b/bridge/core/native/native_loader.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_NATIVE_NATIVE_LOADER_H_ +#define WEBF_CORE_NATIVE_NATIVE_LOADER_H_ + +#include "bindings/qjs/script_promise.h" +#include "bindings/qjs/script_wrappable.h" + +namespace webf { + +class NativeLoader : public ScriptWrappable { + DEFINE_WRAPPERTYPEINFO(); + + public: + using ImplType = NativeLoader*; + + NativeLoader() = delete; + explicit NativeLoader(ExecutingContext* context); + + ScriptPromise loadNativeLibrary(const AtomicString& lib_name, + const ScriptValue& import_object, + ExceptionState& exception_state); +}; + +} // namespace webf + +#endif // WEBF_CORE_NATIVE_NATIVE_LOADER_H_ diff --git a/bridge/core/native/script_value_ref.cc b/bridge/core/native/script_value_ref.cc new file mode 100644 index 0000000000..66eeedee10 --- /dev/null +++ b/bridge/core/native/script_value_ref.cc @@ -0,0 +1,14 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "core/native/script_value_ref.h" + +namespace webf { + +ScriptValueRefPublicMethods* ScriptValueRef::publicMethods() { + static ScriptValueRefPublicMethods public_methods; + return &public_methods; +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/core/native/script_value_ref.h b/bridge/core/native/script_value_ref.h new file mode 100644 index 0000000000..257e303574 --- /dev/null +++ b/bridge/core/native/script_value_ref.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_NATIVE_SCRIPT_VALUE_REF_H_ +#define WEBF_CORE_NATIVE_SCRIPT_VALUE_REF_H_ + +#include "bindings/qjs/script_value.h" +#include "core/executing_context.h" +#include "plugin_api/script_value_ref.h" + +namespace webf { + +struct ScriptValueRef { + static ScriptValueRefPublicMethods* publicMethods(); + + ExecutingContext* context; + ScriptValue script_value; +}; + +} // namespace webf + +#endif // WEBF_CORE_NATIVE_SCRIPT_VALUE_REF_H_ diff --git a/bridge/core/page.cc b/bridge/core/page.cc index 182bbe3053..0f81d49203 100644 --- a/bridge/core/page.cc +++ b/bridge/core/page.cc @@ -127,7 +127,7 @@ void WebFPage::evaluateScript(const char* script, size_t length, const char* url uint8_t* WebFPage::dumpByteCode(const char* script, size_t length, const char* url, uint64_t* byteLength) { if (!context_->IsContextValid()) return nullptr; - return context_->DumpByteCode(script, length, url, byteLength); + return context_->DumpByteCode(script, static_cast(length), url, byteLength); } bool WebFPage::evaluateByteCode(uint8_t* bytes, size_t byteLength) { @@ -153,4 +153,148 @@ void WebFPage::reportError(const char* errmsg) { handler_(context_, errmsg); } +static void ReturnEvaluateScriptsInternal(Dart_PersistentHandle persistent_handle, + EvaluateQuickjsByteCodeCallback result_callback, + bool is_success) { + Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + result_callback(handle, is_success ? 1 : 0); + Dart_DeletePersistentHandle_DL(persistent_handle); +} + +void WebFPage::EvaluateScriptsInternal(void* page_, + const char* code, + uint64_t code_len, + uint8_t** parsed_bytecodes, + uint64_t* bytecode_len, + const char* bundleFilename, + int32_t startLine, + int64_t profile_id, + Dart_Handle persistent_handle, + EvaluateScriptsCallback result_callback) { + auto page = reinterpret_cast(page_); + assert(std::this_thread::get_id() == page->currentThread()); + + page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); + + bool is_success = page->evaluateScript(code, code_len, parsed_bytecodes, bytecode_len, bundleFilename, startLine); + + page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); + + page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnEvaluateScriptsInternal, + persistent_handle, result_callback, is_success); +} + +static void ReturnEvaluateQuickjsByteCodeResultToDart(Dart_PersistentHandle persistent_handle, + EvaluateQuickjsByteCodeCallback result_callback, + bool is_success) { + Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + result_callback(handle, is_success ? 1 : 0); + Dart_DeletePersistentHandle_DL(persistent_handle); +} + +void WebFPage::EvaluateQuickjsByteCodeInternal(void* page_, + uint8_t* bytes, + int32_t byteLen, + int64_t profile_id, + Dart_PersistentHandle persistent_handle, + EvaluateQuickjsByteCodeCallback result_callback) { + auto page = reinterpret_cast(page_); + assert(std::this_thread::get_id() == page->currentThread()); + + page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); + + bool is_success = page->evaluateByteCode(bytes, byteLen); + + page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); + + page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnEvaluateQuickjsByteCodeResultToDart, + persistent_handle, result_callback, is_success); +} + +static void ReturnParseHTMLToDart(Dart_PersistentHandle persistent_handle, ParseHTMLCallback result_callback) { + Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + result_callback(handle); + Dart_DeletePersistentHandle_DL(persistent_handle); +} + +void WebFPage::ParseHTMLInternal(void* page_, + char* code, + int32_t length, + int64_t profile_id, + Dart_PersistentHandle dart_handle, + ParseHTMLCallback result_callback) { + auto page = reinterpret_cast(page_); + assert(std::this_thread::get_id() == page->currentThread()); + + page->dartIsolateContext()->profiler()->StartTrackEvaluation(profile_id); + + page->parseHTML(code, length); + dart_free(code); + + page->dartIsolateContext()->profiler()->FinishTrackEvaluation(profile_id); + + page->dartIsolateContext()->dispatcher()->PostToDart(page->isDedicated(), ReturnParseHTMLToDart, dart_handle, + result_callback); +} + +static void ReturnInvokeEventResultToDart(Dart_Handle persistent_handle, + InvokeModuleEventCallback result_callback, + webf::NativeValue* result) { + Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + result_callback(handle, result); + Dart_DeletePersistentHandle_DL(persistent_handle); +} + +void WebFPage::InvokeModuleEventInternal(void* page_, + void* module_name, + const char* eventType, + void* event, + void* extra, + Dart_Handle persistent_handle, + InvokeModuleEventCallback result_callback) { + auto page = reinterpret_cast(page_); + auto dart_isolate_context = page->executingContext()->dartIsolateContext(); + assert(std::this_thread::get_id() == page->currentThread()); + + page->dartIsolateContext()->profiler()->StartTrackAsyncEvaluation(); + + auto* result = page->invokeModuleEvent(reinterpret_cast(module_name), eventType, event, + reinterpret_cast(extra)); + + page->dartIsolateContext()->profiler()->FinishTrackAsyncEvaluation(); + + dart_isolate_context->dispatcher()->PostToDart(page->isDedicated(), ReturnInvokeEventResultToDart, persistent_handle, + result_callback, result); +} + +static void ReturnDumpByteCodeResultToDart(Dart_Handle persistent_handle, DumpQuickjsByteCodeCallback result_callback) { + Dart_Handle handle = Dart_HandleFromPersistent_DL(persistent_handle); + result_callback(handle); + Dart_DeletePersistentHandle_DL(persistent_handle); +} + +void WebFPage::DumpQuickJsByteCodeInternal(void* page_, + int64_t profile_id, + const char* code, + int32_t code_len, + uint8_t** parsed_bytecodes, + uint64_t* bytecode_len, + const char* url, + Dart_PersistentHandle persistent_handle, + DumpQuickjsByteCodeCallback result_callback) { + auto page = reinterpret_cast(page_); + auto dart_isolate_context = page->executingContext()->dartIsolateContext(); + + dart_isolate_context->profiler()->StartTrackEvaluation(profile_id); + + assert(std::this_thread::get_id() == page->currentThread()); + uint8_t* bytes = page->dumpByteCode(code, code_len, url, bytecode_len); + *parsed_bytecodes = bytes; + + dart_isolate_context->profiler()->FinishTrackEvaluation(profile_id); + + dart_isolate_context->dispatcher()->PostToDart(page->isDedicated(), ReturnDumpByteCodeResultToDart, persistent_handle, + result_callback); +} + } // namespace webf diff --git a/bridge/core/page.h b/bridge/core/page.h index 7b4bf1aa0d..4accd2fd19 100644 --- a/bridge/core/page.h +++ b/bridge/core/page.h @@ -41,6 +41,47 @@ class WebFPage final { // Bytecodes which registered by webf plugins. static std::unordered_map pluginByteCode; + static void EvaluateScriptsInternal(void* page_, + const char* code, + uint64_t code_len, + uint8_t** parsed_bytecodes, + uint64_t* bytecode_len, + const char* bundleFilename, + int32_t startLine, + int64_t profile_id, + Dart_Handle dart_handle, + EvaluateScriptsCallback result_callback); + + static void EvaluateQuickjsByteCodeInternal(void* page_, + uint8_t* bytes, + int32_t byteLen, + int64_t profile_id, + Dart_PersistentHandle persistent_handle, + EvaluateQuickjsByteCodeCallback result_callback); + static void ParseHTMLInternal(void* page_, + char* code, + int32_t length, + int64_t profile_id, + Dart_PersistentHandle dart_handle, + ParseHTMLCallback result_callback); + + static void InvokeModuleEventInternal(void* page_, + void* module_name, + const char* eventType, + void* event, + void* extra, + Dart_Handle dart_handle, + InvokeModuleEventCallback result_callback); + + static void DumpQuickJsByteCodeInternal(void* page_, + int64_t profile_id, + const char* code, + int32_t code_len, + uint8_t** parsed_bytecodes, + uint64_t* bytecode_len, + const char* url, + Dart_PersistentHandle persistent_handle, + DumpQuickjsByteCodeCallback result_callback); // evaluate JavaScript source codes in standard mode. bool evaluateScript(const char* script, diff --git a/bridge/foundation/rust_readable.cc b/bridge/foundation/rust_readable.cc new file mode 100644 index 0000000000..0006d181b5 --- /dev/null +++ b/bridge/foundation/rust_readable.cc @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include +#include +#include "plugin_api/rust_readable.h" + +#if WIN32 +#include +#endif + +namespace webf { + +void* RustReadable::operator new(std::size_t size) { +#if WIN32 + return HeapAlloc(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS, size); +#else + return malloc(size); +#endif +} + +void RustReadable::operator delete(void* memory) noexcept { +#if WIN32 + HeapFree(GetProcessHeap(), 0, memory); +#else +#endif +} + +} // namespace webf \ No newline at end of file diff --git a/bridge/foundation/ui_command_buffer.cc b/bridge/foundation/ui_command_buffer.cc index 3066ae3717..2fc518b251 100644 --- a/bridge/foundation/ui_command_buffer.cc +++ b/bridge/foundation/ui_command_buffer.cc @@ -40,6 +40,8 @@ UICommandKind GetKindFromUICommand(UICommand command) { case UICommand::kStartRecordingCommand: case UICommand::kFinishRecordingCommand: return UICommandKind::kOperation; + default: + return UICommandKind::kUknownCommand; } } @@ -125,7 +127,8 @@ bool UICommandBuffer::empty() { } void UICommandBuffer::clear() { - if (buffer_ == nullptr) return; + if (buffer_ == nullptr) + return; memset(buffer_, 0, sizeof(UICommandItem) * size_); size_ = 0; kind_flag = 0; diff --git a/bridge/foundation/ui_command_buffer.h b/bridge/foundation/ui_command_buffer.h index d8eea269c3..dcfdf0352f 100644 --- a/bridge/foundation/ui_command_buffer.h +++ b/bridge/foundation/ui_command_buffer.h @@ -20,7 +20,8 @@ enum UICommandKind : uint32_t { kEvent = 1 << 4, kAttributeUpdate = 1 << 5, kDisposeBindingObject = 1 << 6, - kOperation = 1 << 7 + kOperation = 1 << 7, + kUknownCommand = 1 << 8 }; enum class UICommand { diff --git a/bridge/foundation/ui_command_strategy.cc b/bridge/foundation/ui_command_strategy.cc index 486d2a4ddc..8fddd6ca32 100644 --- a/bridge/foundation/ui_command_strategy.cc +++ b/bridge/foundation/ui_command_strategy.cc @@ -30,7 +30,7 @@ bool WaitingStatus::IsFullActive() { } void WaitingStatus::SetActiveAtIndex(uint64_t index) { - size_t storage_index = floor(index / 64); + double storage_index = floor(index / 64); if (storage_index < storage.size()) { storage[storage_index] = set_nth_bit_to_zero(storage[storage_index], index % 64); diff --git a/bridge/include/plugin_api/add_event_listener_options.h b/bridge/include/plugin_api/add_event_listener_options.h new file mode 100644 index 0000000000..1d829d0c8b --- /dev/null +++ b/bridge/include/plugin_api/add_event_listener_options.h @@ -0,0 +1,18 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_ADD_EVENT_LISTENER_OPTIONS_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_ADD_EVENT_LISTENER_OPTIONS_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFAddEventListenerOptions { + int32_t capture; + int32_t passive; + int32_t once; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_ADD_EVENT_LISTENER_OPTIONS_H_ diff --git a/bridge/include/plugin_api/animation_event.h b/bridge/include/plugin_api/animation_event.h new file mode 100644 index 0000000000..1d34c80ad6 --- /dev/null +++ b/bridge/include/plugin_api/animation_event.h @@ -0,0 +1,37 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class AnimationEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicAnimationEventGetAnimationName = const char* (*)(AnimationEvent*); +using PublicAnimationEventDupAnimationName = const char* (*)(AnimationEvent*); +using PublicAnimationEventGetElapsedTime = double (*)(AnimationEvent*); +using PublicAnimationEventGetPseudoElement = const char* (*)(AnimationEvent*); +using PublicAnimationEventDupPseudoElement = const char* (*)(AnimationEvent*); +struct AnimationEventPublicMethods : public WebFPublicMethods { + static const char* AnimationName(AnimationEvent* animation_event); + static const char* DupAnimationName(AnimationEvent* animation_event); + static double ElapsedTime(AnimationEvent* animation_event); + static const char* PseudoElement(AnimationEvent* animation_event); + static const char* DupPseudoElement(AnimationEvent* animation_event); + double version{1.0}; + EventPublicMethods event; + PublicAnimationEventGetAnimationName animation_event_get_animation_name{AnimationName}; + PublicAnimationEventDupAnimationName animation_event_dup_animation_name{DupAnimationName}; + PublicAnimationEventGetElapsedTime animation_event_get_elapsed_time{ElapsedTime}; + PublicAnimationEventGetPseudoElement animation_event_get_pseudo_element{PseudoElement}; + PublicAnimationEventDupPseudoElement animation_event_dup_pseudo_element{DupPseudoElement}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_H_ diff --git a/bridge/include/plugin_api/animation_event_init.h b/bridge/include/plugin_api/animation_event_init.h new file mode 100644 index 0000000000..6faa64361f --- /dev/null +++ b/bridge/include/plugin_api/animation_event_init.h @@ -0,0 +1,21 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFAnimationEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + const char* animation_name; + double elapsed_time; + const char* pseudo_element; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_ANIMATION_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/character_data.h b/bridge/include/plugin_api/character_data.h new file mode 100644 index 0000000000..b67ab11cba --- /dev/null +++ b/bridge/include/plugin_api/character_data.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_CHARACTER_DATA_H_ +#define WEBF_CORE_RUST_API_CHARACTER_DATA_H_ + +#include "node.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Event; + +struct CharacterDataPublicMethods : WebFPublicMethods { + double version{1.0}; + NodePublicMethods node; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_CHARACTER_DATA_H_ diff --git a/bridge/include/plugin_api/close_event.h b/bridge/include/plugin_api/close_event.h new file mode 100644 index 0000000000..cb84a70569 --- /dev/null +++ b/bridge/include/plugin_api/close_event.h @@ -0,0 +1,34 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class CloseEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicCloseEventGetCode = int64_t (*)(CloseEvent*); +using PublicCloseEventGetReason = const char* (*)(CloseEvent*); +using PublicCloseEventDupReason = const char* (*)(CloseEvent*); +using PublicCloseEventGetWasClean = int32_t (*)(CloseEvent*); +struct CloseEventPublicMethods : public WebFPublicMethods { + static int64_t Code(CloseEvent* close_event); + static const char* Reason(CloseEvent* close_event); + static const char* DupReason(CloseEvent* close_event); + static int32_t WasClean(CloseEvent* close_event); + double version{1.0}; + EventPublicMethods event; + PublicCloseEventGetCode close_event_get_code{Code}; + PublicCloseEventGetReason close_event_get_reason{Reason}; + PublicCloseEventDupReason close_event_dup_reason{DupReason}; + PublicCloseEventGetWasClean close_event_get_was_clean{WasClean}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_H_ diff --git a/bridge/include/plugin_api/close_event_init.h b/bridge/include/plugin_api/close_event_init.h new file mode 100644 index 0000000000..8b1f3b4c33 --- /dev/null +++ b/bridge/include/plugin_api/close_event_init.h @@ -0,0 +1,21 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFCloseEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + int64_t code; + const char* reason; + int32_t was_clean; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_CLOSE_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/comment.h b/bridge/include/plugin_api/comment.h new file mode 100644 index 0000000000..02570899b7 --- /dev/null +++ b/bridge/include/plugin_api/comment.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_COMMENT_H_ +#define WEBF_CORE_RUST_API_COMMENT_H_ + +#include "character_data.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Event; + +struct CommentPublicMethods : WebFPublicMethods { + double version{1.0}; + CharacterDataPublicMethods character_data; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_COMMENT_H_ diff --git a/bridge/include/plugin_api/container_node.h b/bridge/include/plugin_api/container_node.h new file mode 100644 index 0000000000..1ccdbf7be5 --- /dev/null +++ b/bridge/include/plugin_api/container_node.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_CONTAINER_NODE_H_ +#define WEBF_CORE_RUST_API_CONTAINER_NODE_H_ + +#include "node.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; + +struct ContainerNodePublicMethods : WebFPublicMethods { + double version{1.0}; + NodePublicMethods node; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_CONTAINER_NODE_H_ diff --git a/bridge/include/plugin_api/custom_event.h b/bridge/include/plugin_api/custom_event.h new file mode 100644 index 0000000000..d905a8c48e --- /dev/null +++ b/bridge/include/plugin_api/custom_event.h @@ -0,0 +1,28 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_CUSTOM_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_CUSTOM_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class CustomEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicCustomEventGetDetail = WebFValue (*)(CustomEvent*); +using PublicCustomEventInitCustomEvent = void (*)(CustomEvent*, const char*, int32_t, int32_t, ScriptValueRef*, SharedExceptionState*); +struct CustomEventPublicMethods : public WebFPublicMethods { + static WebFValue Detail(CustomEvent* custom_event); + static void InitCustomEvent(CustomEvent* custom_event, const char* type, int32_t can_bubble, int32_t cancelable, ScriptValueRef* detail, SharedExceptionState* shared_exception_state); + double version{1.0}; + EventPublicMethods event; + PublicCustomEventGetDetail custom_event_get_detail{Detail}; + PublicCustomEventInitCustomEvent custom_event_init_custom_event{InitCustomEvent}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_CUSTOM_EVENT_H_ diff --git a/bridge/include/plugin_api/document.h b/bridge/include/plugin_api/document.h new file mode 100644 index 0000000000..60a41ec864 --- /dev/null +++ b/bridge/include/plugin_api/document.h @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_DOCUMENT_H_ +#define WEBF_CORE_RUST_API_DOCUMENT_H_ + +#include "comment.h" +#include "container_node.h" +#include "document_fragment.h" +#include "element.h" +#include "event.h" +#include "html_element.h" +#include "text.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Element; +class DocumentFragment; +class Document; +class Text; +class Comment; +class Event; + +struct WebFElementCreationOptions { + const char* is; +}; + +using PublicDocumentCreateElement = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentCreateElementWithElementCreationOptions = + WebFValue (*)(Document*, + const char*, + WebFElementCreationOptions&, + SharedExceptionState* shared_exception_state); +using PublicDocumentCreateElementNS = + WebFValue (*)(Document*, + const char*, + const char*, + SharedExceptionState* shared_exception_state); +using PublicDocumentCreateElementNSWithElementCreationOptions = + WebFValue (*)(Document*, + const char*, + const char*, + WebFElementCreationOptions&, + SharedExceptionState* shared_exception_state); +using PublicDocumentCreateTextNode = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentCreateDocumentFragment = + WebFValue (*)(Document*, + SharedExceptionState* shared_exception_state); +using PublicDocumentCreateComment = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentCreateEvent = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentQuerySelector = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentGetElementById = + WebFValue (*)(Document*, const char*, SharedExceptionState* shared_exception_state); +using PublicDocumentElementFromPoint = + WebFValue (*)(Document*, + double, + double, + SharedExceptionState* shared_exception_state); +using PublicDocumentGetDocumentElement = WebFValue (*)(Document*); +using PublicDocumentGetDocumentHeader = WebFValue (*)(Document*); +using PublicDocumentGetDocumentBody = WebFValue (*)(Document*); + +struct DocumentPublicMethods : public WebFPublicMethods { + static WebFValue CreateElement(Document* document, + const char* tag_name, + SharedExceptionState* shared_exception_state); + static WebFValue CreateElementWithElementCreationOptions( + Document* document, + const char* tag_name, + WebFElementCreationOptions& options, + SharedExceptionState* shared_exception_state); + static WebFValue CreateElementNS(Document* document, + const char* uri, + const char* tag_name, + SharedExceptionState* shared_exception_state); + static WebFValue CreateElementNSWithElementCreationOptions( + Document* document, + const char* uri, + const char* tag_name, + WebFElementCreationOptions& options, + SharedExceptionState* shared_exception_state); + static WebFValue CreateTextNode(Document* document, + const char* data, + SharedExceptionState* shared_exception_state); + static WebFValue CreateDocumentFragment( + Document* document, + SharedExceptionState* shared_exception_state); + static WebFValue CreateComment(Document* document, + const char* data, + SharedExceptionState* shared_exception_state); + static WebFValue CreateEvent(Document* document, + const char* type, + SharedExceptionState* shared_exception_state); + static WebFValue QuerySelector(Document* document, + const char* selectors, + SharedExceptionState* shared_exception_state); + static WebFValue GetElementById(Document* document, + const char* id, + SharedExceptionState* shared_exception_state); + static WebFValue ElementFromPoint(Document* document, + double x, + double y, + SharedExceptionState* shared_exception_state); + static WebFValue DocumentElement(Document* document); + static WebFValue Head(Document* document); + static WebFValue Body(Document* document); + + double version{1.0}; + ContainerNodePublicMethods container_node; + PublicDocumentCreateElement document_create_element{CreateElement}; + PublicDocumentCreateElementWithElementCreationOptions document_create_element_with_element_creation_options{ + CreateElementWithElementCreationOptions}; + PublicDocumentCreateElementNS document_create_element_ns{CreateElementNS}; + PublicDocumentCreateElementNSWithElementCreationOptions document_create_element_ns_with_element_creation_options{ + CreateElementNSWithElementCreationOptions}; + PublicDocumentCreateTextNode document_create_text_node{CreateTextNode}; + PublicDocumentCreateDocumentFragment document_create_document_fragment{CreateDocumentFragment}; + PublicDocumentCreateComment document_create_comment{CreateComment}; + PublicDocumentCreateEvent document_create_event{CreateEvent}; + PublicDocumentQuerySelector document_query_selector{QuerySelector}; + PublicDocumentGetElementById document_get_element_by_id{GetElementById}; + PublicDocumentElementFromPoint document_element_from_point{ElementFromPoint}; + PublicDocumentGetDocumentElement document_get_document_element{DocumentElement}; + PublicDocumentGetDocumentHeader document_get_document_header{Head}; + PublicDocumentGetDocumentBody document_get_document_body{Body}; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_DOCUMENT_H_ diff --git a/bridge/include/plugin_api/document_fragment.h b/bridge/include/plugin_api/document_fragment.h new file mode 100644 index 0000000000..5a97e17bad --- /dev/null +++ b/bridge/include/plugin_api/document_fragment.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_DOCUMENT_FRAGMENT_H_ +#define WEBF_CORE_RUST_API_DOCUMENT_FRAGMENT_H_ + +#include "container_node.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class DocumentFragment; +class Document; + +struct DocumentFragmentPublicMethods : WebFPublicMethods { + double version{1.0}; + ContainerNodePublicMethods container_node; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_DOCUMENT_FRAGMENT_H_ diff --git a/bridge/include/plugin_api/element.h b/bridge/include/plugin_api/element.h new file mode 100644 index 0000000000..5e9fbb4e49 --- /dev/null +++ b/bridge/include/plugin_api/element.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_ELEMENT_H_ +#define WEBF_CORE_RUST_API_ELEMENT_H_ + +#include "container_node.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Element; +class Document; + +struct ElementPublicMethods : WebFPublicMethods { + double version{1.0}; + ContainerNodePublicMethods container_node; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_ELEMENT_H_ diff --git a/bridge/include/plugin_api/event.h b/bridge/include/plugin_api/event.h new file mode 100644 index 0000000000..5450a9d9ae --- /dev/null +++ b/bridge/include/plugin_api/event.h @@ -0,0 +1,74 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_H_ +#include +#include "script_value_ref.h" +#include "webf_value.h" +namespace webf { +class EventTarget; +typedef struct EventTargetPublicMethods EventTargetPublicMethods; +class SharedExceptionState; +class ExecutingContext; +class Event; +typedef struct ScriptValueRef ScriptValueRef; +using PublicEventGetBubbles = int32_t (*)(Event*); +using PublicEventGetCancelBubble = int32_t (*)(Event*); +using PublicEventSetCancelBubble = void (*)(Event*, int32_t, SharedExceptionState*); +using PublicEventGetCancelable = int32_t (*)(Event*); +using PublicEventGetCurrentTarget = WebFValue (*)(Event*); +using PublicEventGetDefaultPrevented = int32_t (*)(Event*); +using PublicEventGetSrcElement = WebFValue (*)(Event*); +using PublicEventGetTarget = WebFValue (*)(Event*); +using PublicEventGetIsTrusted = int32_t (*)(Event*); +using PublicEventGetTimeStamp = double (*)(Event*); +using PublicEventGetType = const char* (*)(Event*); +using PublicEventDupType = const char* (*)(Event*); +using PublicEventInitEvent = void (*)(Event*, const char*, int32_t, int32_t, SharedExceptionState*); +using PublicEventPreventDefault = void (*)(Event*, SharedExceptionState*); +using PublicEventStopImmediatePropagation = void (*)(Event*, SharedExceptionState*); +using PublicEventStopPropagation = void (*)(Event*, SharedExceptionState*); +using PublicEventRelease = void (*)(Event*); +struct EventPublicMethods : public WebFPublicMethods { + static int32_t Bubbles(Event* event); + static int32_t CancelBubble(Event* event); + static void SetCancelBubble(Event* event, int32_t cancelBubble, SharedExceptionState* shared_exception_state); + static int32_t Cancelable(Event* event); + static WebFValue CurrentTarget(Event* event); + static int32_t DefaultPrevented(Event* event); + static WebFValue SrcElement(Event* event); + static WebFValue Target(Event* event); + static int32_t IsTrusted(Event* event); + static double TimeStamp(Event* event); + static const char* Type(Event* event); + static const char* DupType(Event* event); + static void InitEvent(Event* event, const char* type, int32_t bubbles, int32_t cancelable, SharedExceptionState* shared_exception_state); + static void PreventDefault(Event* event, SharedExceptionState* shared_exception_state); + static void StopImmediatePropagation(Event* event, SharedExceptionState* shared_exception_state); + static void StopPropagation(Event* event, SharedExceptionState* shared_exception_state); + static void Release(Event* event); + double version{1.0}; + PublicEventGetBubbles event_get_bubbles{Bubbles}; + PublicEventGetCancelBubble event_get_cancel_bubble{CancelBubble}; + PublicEventSetCancelBubble event_set_cancel_bubble{SetCancelBubble}; + PublicEventGetCancelable event_get_cancelable{Cancelable}; + PublicEventGetCurrentTarget event_get_current_target{CurrentTarget}; + PublicEventGetDefaultPrevented event_get_default_prevented{DefaultPrevented}; + PublicEventGetSrcElement event_get_src_element{SrcElement}; + PublicEventGetTarget event_get_target{Target}; + PublicEventGetIsTrusted event_get_is_trusted{IsTrusted}; + PublicEventGetTimeStamp event_get_time_stamp{TimeStamp}; + PublicEventGetType event_get_type{Type}; + PublicEventDupType event_dup_type{DupType}; + PublicEventInitEvent event_init_event{InitEvent}; + PublicEventPreventDefault event_prevent_default{PreventDefault}; + PublicEventStopImmediatePropagation event_stop_immediate_propagation{StopImmediatePropagation}; + PublicEventStopPropagation event_stop_propagation{StopPropagation}; + PublicEventRelease event_release{Release}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_H_ diff --git a/bridge/include/plugin_api/event_init.h b/bridge/include/plugin_api/event_init.h new file mode 100644 index 0000000000..e4d94893cc --- /dev/null +++ b/bridge/include/plugin_api/event_init.h @@ -0,0 +1,18 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/event_listener_options.h b/bridge/include/plugin_api/event_listener_options.h new file mode 100644 index 0000000000..233ad4fef4 --- /dev/null +++ b/bridge/include/plugin_api/event_listener_options.h @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_LISTENER_OPTIONS_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_LISTENER_OPTIONS_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFEventListenerOptions { + int32_t capture; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_EVENT_LISTENER_OPTIONS_H_ diff --git a/bridge/include/plugin_api/event_target.h b/bridge/include/plugin_api/event_target.h new file mode 100644 index 0000000000..3a58f6dc93 --- /dev/null +++ b/bridge/include/plugin_api/event_target.h @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_WEBF_API_EVENT_TARGET_H_ +#define WEBF_CORE_WEBF_API_EVENT_TARGET_H_ + +#include "webf_value.h" +#include "plugin_api/rust_readable.h" + +namespace webf { + +typedef struct WebFAddEventListenerOptions WebFAddEventListenerOptions; +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Event; +typedef struct EventPublicMethods EventPublicMethods; +typedef struct WebFEventListenerContext WebFEventListenerContext; + +using WebFImplEventCallback = void (*)(WebFEventListenerContext* callback_context, + Event* event, + const EventPublicMethods* event_methods, + WebFValueStatus* status, + SharedExceptionState* shared_exception_state); +using FreePtrFn = void (*)(WebFEventListenerContext* callback_context); + +enum class EventTargetType { + kEventTarget = 0, + kNode = 1, + kContainerNode = 2, + kWindow = 3, + kDocument = 4, + kElement = 5, + HTMLElement = 6, + kHTMLImageElement = 7, + kHTMLCanvasElement = 8, + kHTMLDivElement = 9, + kHTMLScriptElement = 10, + kDocumentFragment = 11, + kText = 12, + kComment = 13, +}; + +struct WebFEventListenerContext : public RustReadable { + WebFImplEventCallback callback; + FreePtrFn free_ptr; + void* ptr; +}; + +using PublicEventTargetAddEventListener = void (*)(EventTarget* event_target, + const char*, + WebFEventListenerContext* callback_context, + WebFAddEventListenerOptions* options, + SharedExceptionState* shared_exception_state); +using PublicEventTargetRemoveEventListener = void (*)(EventTarget* event_target, + const char*, + WebFEventListenerContext* callback_context, + SharedExceptionState* shared_exception_state); +using PublicEventTargetDispatchEvent = bool (*)(EventTarget* event_target, + Event* event, + SharedExceptionState* shared_exception_state); + +using PublicEventTargetRelease = void (*)(EventTarget*); + +using PublicEventTargetDynamicTo = WebFValue (*)(EventTarget*, + EventTargetType event_target_type); + +struct EventTargetPublicMethods : public WebFPublicMethods { + static void AddEventListener(EventTarget* event_target, + const char* event_name_str, + WebFEventListenerContext* callback_context, + WebFAddEventListenerOptions* options, + SharedExceptionState* shared_exception_state); + static void RemoveEventListener(EventTarget* event_target, + const char* event_name_str, + WebFEventListenerContext* callback_context, + SharedExceptionState* shared_exception_state); + static bool DispatchEvent(EventTarget* event_target, Event* event, SharedExceptionState* shared_exception_state); + static void Release(EventTarget* event_target); + static WebFValue DynamicTo(EventTarget* event_target, + EventTargetType event_target_type); + + double version{1.0}; + PublicEventTargetAddEventListener event_target_add_event_listener{AddEventListener}; + PublicEventTargetRemoveEventListener event_target_remove_event_listener{RemoveEventListener}; + PublicEventTargetDispatchEvent event_target_dispatch_event{DispatchEvent}; + PublicEventTargetRelease event_target_release{Release}; + PublicEventTargetDynamicTo event_target_dynamic_to{DynamicTo}; +}; + +} // namespace webf + +#endif // WEBF_CORE_WEBF_API_EVENT_TARGET_H_ diff --git a/bridge/include/plugin_api/exception_state.h b/bridge/include/plugin_api/exception_state.h new file mode 100644 index 0000000000..99c4929c51 --- /dev/null +++ b/bridge/include/plugin_api/exception_state.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_EXCEPTION_STATE_H_ +#define WEBF_CORE_RUST_API_EXCEPTION_STATE_H_ + +#include +#include "bindings/qjs/exception_state.h" +#include "webf_value.h" + +namespace webf { + +class ExecutingContext; +class SharedExceptionState; + +using PublicExceptionStateHasException = bool (*)(SharedExceptionState* shared_exception_state); +using PublicExceptionStateStringify = void (*)(ExecutingContext* context, + SharedExceptionState* shared_exception_state, + char** errmsg, + uint32_t* strlen); + +class ExceptionStatePublicMethods : public WebFPublicMethods { + static bool HasException(SharedExceptionState* shared_exception_state); + static void Stringify(ExecutingContext* context, + SharedExceptionState* shared_exception_state, + char** errmsg, + uint32_t* strlen); + + double version{1.0}; + PublicExceptionStateHasException has_exception_{HasException}; + PublicExceptionStateStringify stringify_{Stringify}; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_EXCEPTION_STATE_H_ diff --git a/bridge/include/plugin_api/executing_context.h b/bridge/include/plugin_api/executing_context.h new file mode 100644 index 0000000000..5f3f8d5466 --- /dev/null +++ b/bridge/include/plugin_api/executing_context.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_EXECUTING_CONTEXT_H_ +#define WEBF_CORE_RUST_API_EXECUTING_CONTEXT_H_ + +#include "document.h" +#include "exception_state.h" +#include "window.h" + +namespace webf { + +class Document; +class ExecutingContext; +class Window; + +using PublicContextGetDocument = WebFValue (*)(ExecutingContext*); +using PublicContextGetWindow = WebFValue (*)(ExecutingContext*); +using PublicContextGetExceptionState = WebFValue (*)(); + +// Memory aligned and readable from WebF side. +// Only C type member can be included in this class, any C++ type and classes can is not allowed to use here. +struct ExecutingContextWebFMethods { + static WebFValue document(ExecutingContext* context); + static WebFValue window(ExecutingContext* context); + static WebFValue CreateExceptionState(); + + double version{1.0}; + PublicContextGetDocument rust_context_get_document_{document}; + PublicContextGetWindow rust_context_get_window_{window}; + PublicContextGetExceptionState rust_context_get_exception_state_{CreateExceptionState}; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_EXECUTING_CONTEXT_H_ diff --git a/bridge/include/plugin_api/focus_event.h b/bridge/include/plugin_api/focus_event.h new file mode 100644 index 0000000000..90b3190d1d --- /dev/null +++ b/bridge/include/plugin_api/focus_event.h @@ -0,0 +1,27 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_H_ +#include +#include "script_value_ref.h" +#include "ui_event.h" +namespace webf { +class EventTarget; +typedef struct EventTargetPublicMethods EventTargetPublicMethods; +class SharedExceptionState; +class ExecutingContext; +class FocusEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicFocusEventGetRelatedTarget = WebFValue (*)(FocusEvent*); +struct FocusEventPublicMethods : public WebFPublicMethods { + static WebFValue RelatedTarget(FocusEvent* focus_event); + double version{1.0}; + UIEventPublicMethods ui_event; + PublicFocusEventGetRelatedTarget focus_event_get_related_target{RelatedTarget}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_H_ diff --git a/bridge/include/plugin_api/focus_event_init.h b/bridge/include/plugin_api/focus_event_init.h new file mode 100644 index 0000000000..f01803cb83 --- /dev/null +++ b/bridge/include/plugin_api/focus_event_init.h @@ -0,0 +1,23 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct EventTarget EventTarget; +typedef struct EventTargetPublicMethods EventTargetPublicMethods; +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFFocusEventInit { + double detail; + WebFValue view; + double which; + WebFValue related_target; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_FOCUS_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/gesture_event.h b/bridge/include/plugin_api/gesture_event.h new file mode 100644 index 0000000000..a3b58d2703 --- /dev/null +++ b/bridge/include/plugin_api/gesture_event.h @@ -0,0 +1,52 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class GestureEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicGestureEventGetState = const char* (*)(GestureEvent*); +using PublicGestureEventDupState = const char* (*)(GestureEvent*); +using PublicGestureEventGetDirection = const char* (*)(GestureEvent*); +using PublicGestureEventDupDirection = const char* (*)(GestureEvent*); +using PublicGestureEventGetDeltaX = double (*)(GestureEvent*); +using PublicGestureEventGetDeltaY = double (*)(GestureEvent*); +using PublicGestureEventGetVelocityX = double (*)(GestureEvent*); +using PublicGestureEventGetVelocityY = double (*)(GestureEvent*); +using PublicGestureEventGetScale = double (*)(GestureEvent*); +using PublicGestureEventGetRotation = double (*)(GestureEvent*); +struct GestureEventPublicMethods : public WebFPublicMethods { + static const char* State(GestureEvent* gesture_event); + static const char* DupState(GestureEvent* gesture_event); + static const char* Direction(GestureEvent* gesture_event); + static const char* DupDirection(GestureEvent* gesture_event); + static double DeltaX(GestureEvent* gesture_event); + static double DeltaY(GestureEvent* gesture_event); + static double VelocityX(GestureEvent* gesture_event); + static double VelocityY(GestureEvent* gesture_event); + static double Scale(GestureEvent* gesture_event); + static double Rotation(GestureEvent* gesture_event); + double version{1.0}; + EventPublicMethods event; + PublicGestureEventGetState gesture_event_get_state{State}; + PublicGestureEventDupState gesture_event_dup_state{DupState}; + PublicGestureEventGetDirection gesture_event_get_direction{Direction}; + PublicGestureEventDupDirection gesture_event_dup_direction{DupDirection}; + PublicGestureEventGetDeltaX gesture_event_get_delta_x{DeltaX}; + PublicGestureEventGetDeltaY gesture_event_get_delta_y{DeltaY}; + PublicGestureEventGetVelocityX gesture_event_get_velocity_x{VelocityX}; + PublicGestureEventGetVelocityY gesture_event_get_velocity_y{VelocityY}; + PublicGestureEventGetScale gesture_event_get_scale{Scale}; + PublicGestureEventGetRotation gesture_event_get_rotation{Rotation}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_H_ diff --git a/bridge/include/plugin_api/gesture_event_init.h b/bridge/include/plugin_api/gesture_event_init.h new file mode 100644 index 0000000000..a8b11547aa --- /dev/null +++ b/bridge/include/plugin_api/gesture_event_init.h @@ -0,0 +1,26 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFGestureEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + const char* state; + const char* direction; + double delta_x; + double delta_y; + double velocity_x; + double velocity_y; + double scale; + double rotation; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_GESTURE_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/hashchange_event.h b/bridge/include/plugin_api/hashchange_event.h new file mode 100644 index 0000000000..2c70909244 --- /dev/null +++ b/bridge/include/plugin_api/hashchange_event.h @@ -0,0 +1,34 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class HashchangeEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicHashchangeEventGetNewURL = const char* (*)(HashchangeEvent*); +using PublicHashchangeEventDupNewURL = const char* (*)(HashchangeEvent*); +using PublicHashchangeEventGetOldURL = const char* (*)(HashchangeEvent*); +using PublicHashchangeEventDupOldURL = const char* (*)(HashchangeEvent*); +struct HashchangeEventPublicMethods : public WebFPublicMethods { + static const char* NewURL(HashchangeEvent* hashchange_event); + static const char* DupNewURL(HashchangeEvent* hashchange_event); + static const char* OldURL(HashchangeEvent* hashchange_event); + static const char* DupOldURL(HashchangeEvent* hashchange_event); + double version{1.0}; + EventPublicMethods event; + PublicHashchangeEventGetNewURL hashchange_event_get_new_url{NewURL}; + PublicHashchangeEventDupNewURL hashchange_event_dup_new_url{DupNewURL}; + PublicHashchangeEventGetOldURL hashchange_event_get_old_url{OldURL}; + PublicHashchangeEventDupOldURL hashchange_event_dup_old_url{DupOldURL}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_H_ diff --git a/bridge/include/plugin_api/hashchange_event_init.h b/bridge/include/plugin_api/hashchange_event_init.h new file mode 100644 index 0000000000..2b949c1144 --- /dev/null +++ b/bridge/include/plugin_api/hashchange_event_init.h @@ -0,0 +1,20 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFHashchangeEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + const char* old_url; + const char* new_url; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_HASHCHANGE_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/html_canvas_element.h b/bridge/include/plugin_api/html_canvas_element.h new file mode 100644 index 0000000000..3ccccd27e8 --- /dev/null +++ b/bridge/include/plugin_api/html_canvas_element.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_HTML_CANVAS_ELEMENT_H_ +#define WEBF_CORE_RUST_API_HTML_CANVAS_ELEMENT_H_ + +#include "html_element.h" + +namespace webf { + +struct HTMLCanvasElementPublicMethods : WebFPublicMethods { + double version{1.0}; + HTMLElementPublicMethods html_element_public_methods; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_HTML_CANVAS_ELEMENT_H_ diff --git a/bridge/include/plugin_api/html_element.h b/bridge/include/plugin_api/html_element.h new file mode 100644 index 0000000000..fa41ad82c6 --- /dev/null +++ b/bridge/include/plugin_api/html_element.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_HTML_ELEMENT_H_ +#define WEBF_CORE_RUST_API_HTML_ELEMENT_H_ + +#include "element.h" + +namespace webf { + +struct HTMLElementPublicMethods : WebFPublicMethods { + double version{1.0}; + ElementPublicMethods element_public_methods; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_HTML_ELEMENT_H_ diff --git a/bridge/include/plugin_api/html_image_element.h b/bridge/include/plugin_api/html_image_element.h new file mode 100644 index 0000000000..601fff751d --- /dev/null +++ b/bridge/include/plugin_api/html_image_element.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_HTML_IMAGE_ELEMENT_H_ +#define WEBF_CORE_RUST_API_HTML_IMAGE_ELEMENT_H_ + +#include "html_element.h" + +namespace webf { + +struct HTMLImageElementPublicMethods : WebFPublicMethods { + double version{1.0}; + HTMLElementPublicMethods html_element_public_methods; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_HTML_IMAGE_ELEMENT_H_ diff --git a/bridge/include/plugin_api/input_event.h b/bridge/include/plugin_api/input_event.h new file mode 100644 index 0000000000..00b1212bad --- /dev/null +++ b/bridge/include/plugin_api/input_event.h @@ -0,0 +1,34 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_H_ +#include +#include "script_value_ref.h" +#include "ui_event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class InputEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicInputEventGetInputType = const char* (*)(InputEvent*); +using PublicInputEventDupInputType = const char* (*)(InputEvent*); +using PublicInputEventGetData = const char* (*)(InputEvent*); +using PublicInputEventDupData = const char* (*)(InputEvent*); +struct InputEventPublicMethods : public WebFPublicMethods { + static const char* InputType(InputEvent* input_event); + static const char* DupInputType(InputEvent* input_event); + static const char* Data(InputEvent* input_event); + static const char* DupData(InputEvent* input_event); + double version{1.0}; + UIEventPublicMethods ui_event; + PublicInputEventGetInputType input_event_get_input_type{InputType}; + PublicInputEventDupInputType input_event_dup_input_type{DupInputType}; + PublicInputEventGetData input_event_get_data{Data}; + PublicInputEventDupData input_event_dup_data{DupData}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_H_ diff --git a/bridge/include/plugin_api/input_event_init.h b/bridge/include/plugin_api/input_event_init.h new file mode 100644 index 0000000000..5a0d73ee61 --- /dev/null +++ b/bridge/include/plugin_api/input_event_init.h @@ -0,0 +1,22 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFInputEventInit { + double detail; + WebFValue view; + double which; + const char* input_type; + const char* data; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_INPUT_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/intersection_change_event.h b/bridge/include/plugin_api/intersection_change_event.h new file mode 100644 index 0000000000..8dd91cde9b --- /dev/null +++ b/bridge/include/plugin_api/intersection_change_event.h @@ -0,0 +1,25 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class IntersectionChangeEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicIntersectionChangeEventGetIntersectionRatio = double (*)(IntersectionChangeEvent*); +struct IntersectionChangeEventPublicMethods : public WebFPublicMethods { + static double IntersectionRatio(IntersectionChangeEvent* intersection_change_event); + double version{1.0}; + EventPublicMethods event; + PublicIntersectionChangeEventGetIntersectionRatio intersection_change_event_get_intersection_ratio{IntersectionRatio}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_H_ diff --git a/bridge/include/plugin_api/intersection_change_event_init.h b/bridge/include/plugin_api/intersection_change_event_init.h new file mode 100644 index 0000000000..a4097cf603 --- /dev/null +++ b/bridge/include/plugin_api/intersection_change_event_init.h @@ -0,0 +1,21 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFIntersectionChangeEventInit { + double detail; + WebFValue view; + double which; + double intersection_ratio; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_INTERSECTION_CHANGE_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/keyboard_event_init.h b/bridge/include/plugin_api/keyboard_event_init.h new file mode 100644 index 0000000000..d681a3b016 --- /dev/null +++ b/bridge/include/plugin_api/keyboard_event_init.h @@ -0,0 +1,31 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_KEYBOARD_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_KEYBOARD_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFKeyboardEventInit { + double detail; + WebFValue view; + double which; + int32_t alt_key; + double char_code; + const char* code; + int32_t ctrl_key; + int32_t is_composing; + const char* key; + double key_code; + double location; + int32_t meta_key; + int32_t repeat; + int32_t shift_key; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_KEYBOARD_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/mouse_event.h b/bridge/include/plugin_api/mouse_event.h new file mode 100644 index 0000000000..bf6c6f07c8 --- /dev/null +++ b/bridge/include/plugin_api/mouse_event.h @@ -0,0 +1,34 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_H_ +#include +#include "script_value_ref.h" +#include "ui_event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class MouseEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicMouseEventGetClientX = double (*)(MouseEvent*); +using PublicMouseEventGetClientY = double (*)(MouseEvent*); +using PublicMouseEventGetOffsetX = double (*)(MouseEvent*); +using PublicMouseEventGetOffsetY = double (*)(MouseEvent*); +struct MouseEventPublicMethods : public WebFPublicMethods { + static double ClientX(MouseEvent* mouse_event); + static double ClientY(MouseEvent* mouse_event); + static double OffsetX(MouseEvent* mouse_event); + static double OffsetY(MouseEvent* mouse_event); + double version{1.0}; + UIEventPublicMethods ui_event; + PublicMouseEventGetClientX mouse_event_get_client_x{ClientX}; + PublicMouseEventGetClientY mouse_event_get_client_y{ClientY}; + PublicMouseEventGetOffsetX mouse_event_get_offset_x{OffsetX}; + PublicMouseEventGetOffsetY mouse_event_get_offset_y{OffsetY}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_H_ diff --git a/bridge/include/plugin_api/mouse_event_init.h b/bridge/include/plugin_api/mouse_event_init.h new file mode 100644 index 0000000000..71e04722a4 --- /dev/null +++ b/bridge/include/plugin_api/mouse_event_init.h @@ -0,0 +1,20 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFMouseEventInit { + double detail; + WebFValue view; + double which; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_MOUSE_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/node.h b/bridge/include/plugin_api/node.h new file mode 100644 index 0000000000..a2f02fcfff --- /dev/null +++ b/bridge/include/plugin_api/node.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_NODE_H_ +#define WEBF_CORE_RUST_API_NODE_H_ + +#include "event_target.h" + +namespace webf { + +class EventTarget; +class Node; +class SharedExceptionState; +class ExecutingContext; +class Event; + +struct NodePublicMethods; + +using PublicNodeAppendChild = WebFValue (*)(Node* self_node, + Node* new_node, + SharedExceptionState* shared_exception_state); + +using PublicNodeRemoveChild = WebFValue (*)(Node* self_node, + Node* target_node, + SharedExceptionState* shared_exception_state); + +struct NodePublicMethods : WebFPublicMethods { + explicit NodePublicMethods(); + + static WebFValue AppendChild(Node* self_node, + Node* new_node, + SharedExceptionState* shared_exception_state); + static WebFValue RemoveChild(Node* self_node, + Node* target_node, + SharedExceptionState* shared_exception_state); + double version{1.0}; + EventTargetPublicMethods event_target; + PublicNodeAppendChild rust_node_append_child{AppendChild}; + PublicNodeRemoveChild public_node_remove_child{RemoveChild}; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_NODE_H_ diff --git a/bridge/include/plugin_api/pointer_event.h b/bridge/include/plugin_api/pointer_event.h new file mode 100644 index 0000000000..44f738f501 --- /dev/null +++ b/bridge/include/plugin_api/pointer_event.h @@ -0,0 +1,55 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_H_ +#include +#include "script_value_ref.h" +#include "mouse_event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class PointerEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicPointerEventGetHeight = double (*)(PointerEvent*); +using PublicPointerEventGetIsPrimary = int32_t (*)(PointerEvent*); +using PublicPointerEventGetPointerId = double (*)(PointerEvent*); +using PublicPointerEventGetPointerType = const char* (*)(PointerEvent*); +using PublicPointerEventDupPointerType = const char* (*)(PointerEvent*); +using PublicPointerEventGetPressure = double (*)(PointerEvent*); +using PublicPointerEventGetTangentialPressure = double (*)(PointerEvent*); +using PublicPointerEventGetTiltX = double (*)(PointerEvent*); +using PublicPointerEventGetTiltY = double (*)(PointerEvent*); +using PublicPointerEventGetTwist = double (*)(PointerEvent*); +using PublicPointerEventGetWidth = double (*)(PointerEvent*); +struct PointerEventPublicMethods : public WebFPublicMethods { + static double Height(PointerEvent* pointer_event); + static int32_t IsPrimary(PointerEvent* pointer_event); + static double PointerId(PointerEvent* pointer_event); + static const char* PointerType(PointerEvent* pointer_event); + static const char* DupPointerType(PointerEvent* pointer_event); + static double Pressure(PointerEvent* pointer_event); + static double TangentialPressure(PointerEvent* pointer_event); + static double TiltX(PointerEvent* pointer_event); + static double TiltY(PointerEvent* pointer_event); + static double Twist(PointerEvent* pointer_event); + static double Width(PointerEvent* pointer_event); + double version{1.0}; + MouseEventPublicMethods mouse_event; + PublicPointerEventGetHeight pointer_event_get_height{Height}; + PublicPointerEventGetIsPrimary pointer_event_get_is_primary{IsPrimary}; + PublicPointerEventGetPointerId pointer_event_get_pointer_id{PointerId}; + PublicPointerEventGetPointerType pointer_event_get_pointer_type{PointerType}; + PublicPointerEventDupPointerType pointer_event_dup_pointer_type{DupPointerType}; + PublicPointerEventGetPressure pointer_event_get_pressure{Pressure}; + PublicPointerEventGetTangentialPressure pointer_event_get_tangential_pressure{TangentialPressure}; + PublicPointerEventGetTiltX pointer_event_get_tilt_x{TiltX}; + PublicPointerEventGetTiltY pointer_event_get_tilt_y{TiltY}; + PublicPointerEventGetTwist pointer_event_get_twist{Twist}; + PublicPointerEventGetWidth pointer_event_get_width{Width}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_H_ diff --git a/bridge/include/plugin_api/pointer_event_init.h b/bridge/include/plugin_api/pointer_event_init.h new file mode 100644 index 0000000000..0e6bd769e1 --- /dev/null +++ b/bridge/include/plugin_api/pointer_event_init.h @@ -0,0 +1,25 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFPointerEventInit { + int32_t is_primary; + double pointer_id; + const char* pointer_type; + double pressure; + double tangential_pressure; + double tilt_x; + double tilt_y; + double twist; + double width; + double height; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_POINTER_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/rust_readable.h b/bridge/include/plugin_api/rust_readable.h new file mode 100644 index 0000000000..8bcca1c7d9 --- /dev/null +++ b/bridge/include/plugin_api/rust_readable.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef RUST_READABLE_H +#define RUST_READABLE_H + +#include +#include +#include + +namespace webf { + +// Shared C struct which can be read by rust through Dart FFI. +struct RustReadable { + // Dart FFI use ole32 as it's allocator, we need to override the default allocator to compact with Dart FFI. + static void* operator new(std::size_t size); + static void operator delete(void* memory) noexcept; +}; + +} // namespace webf + +#endif // RUST_READABLE_H diff --git a/bridge/include/plugin_api/script_value_ref.h b/bridge/include/plugin_api/script_value_ref.h new file mode 100644 index 0000000000..349bc5bd6e --- /dev/null +++ b/bridge/include/plugin_api/script_value_ref.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_INCLUDE_PLUGIN_API_SCRIPT_VALUE_REF_H_ +#define WEBF_INCLUDE_PLUGIN_API_SCRIPT_VALUE_REF_H_ + +#include "webf_value.h" + +namespace webf { + +typedef struct ScriptValueRef ScriptValueRef; + +using PublicScriptValueRefRelease = void (*)(ScriptValueRef*); + +struct ScriptValueRefPublicMethods : WebFPublicMethods { + static void Release(ScriptValueRef* script_value_ref); + PublicScriptValueRefRelease release{Release}; +}; + +} // namespace webf + +#endif // WEBF_INCLUDE_PLUGIN_API_SCRIPT_VALUE_REF_H_ diff --git a/bridge/include/plugin_api/scroll_options.h b/bridge/include/plugin_api/scroll_options.h new file mode 100644 index 0000000000..343a100d73 --- /dev/null +++ b/bridge/include/plugin_api/scroll_options.h @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_OPTIONS_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_OPTIONS_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFScrollOptions { + const char* behavior; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_OPTIONS_H_ diff --git a/bridge/include/plugin_api/scroll_to_options.h b/bridge/include/plugin_api/scroll_to_options.h new file mode 100644 index 0000000000..60a1157f46 --- /dev/null +++ b/bridge/include/plugin_api/scroll_to_options.h @@ -0,0 +1,18 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_TO_OPTIONS_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_TO_OPTIONS_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFScrollToOptions { + const char* behavior; + const double top; + const double left; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_SCROLL_TO_OPTIONS_H_ diff --git a/bridge/include/plugin_api/text.h b/bridge/include/plugin_api/text.h new file mode 100644 index 0000000000..83c7706d8b --- /dev/null +++ b/bridge/include/plugin_api/text.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_TEXT_H_ +#define WEBF_CORE_RUST_API_TEXT_H_ + +#include "character_data.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Event; + +struct TextNodePublicMethods : WebFPublicMethods { + double version{1.0}; + CharacterDataPublicMethods character_data; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_TEXT_H_ diff --git a/bridge/include/plugin_api/touch_init.h b/bridge/include/plugin_api/touch_init.h new file mode 100644 index 0000000000..71ca3447a5 --- /dev/null +++ b/bridge/include/plugin_api/touch_init.h @@ -0,0 +1,29 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_TOUCH_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_TOUCH_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct EventTarget EventTarget; +typedef struct EventTargetPublicMethods EventTargetPublicMethods; +struct WebFTouchInit { + double identifier; + WebFValue target; + double client_x; + double client_y; + double screen_x; + double screen_y; + double page_x; + double page_y; + double radius_x; + double radius_y; + double rotation_angle; + double force; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_TOUCH_INIT_H_ diff --git a/bridge/include/plugin_api/transition_event.h b/bridge/include/plugin_api/transition_event.h new file mode 100644 index 0000000000..7d6223f89d --- /dev/null +++ b/bridge/include/plugin_api/transition_event.h @@ -0,0 +1,37 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class SharedExceptionState; +class ExecutingContext; +class TransitionEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicTransitionEventGetElapsedTime = double (*)(TransitionEvent*); +using PublicTransitionEventGetPropertyName = const char* (*)(TransitionEvent*); +using PublicTransitionEventDupPropertyName = const char* (*)(TransitionEvent*); +using PublicTransitionEventGetPseudoElement = const char* (*)(TransitionEvent*); +using PublicTransitionEventDupPseudoElement = const char* (*)(TransitionEvent*); +struct TransitionEventPublicMethods : public WebFPublicMethods { + static double ElapsedTime(TransitionEvent* transition_event); + static const char* PropertyName(TransitionEvent* transition_event); + static const char* DupPropertyName(TransitionEvent* transition_event); + static const char* PseudoElement(TransitionEvent* transition_event); + static const char* DupPseudoElement(TransitionEvent* transition_event); + double version{1.0}; + EventPublicMethods event; + PublicTransitionEventGetElapsedTime transition_event_get_elapsed_time{ElapsedTime}; + PublicTransitionEventGetPropertyName transition_event_get_property_name{PropertyName}; + PublicTransitionEventDupPropertyName transition_event_dup_property_name{DupPropertyName}; + PublicTransitionEventGetPseudoElement transition_event_get_pseudo_element{PseudoElement}; + PublicTransitionEventDupPseudoElement transition_event_dup_pseudo_element{DupPseudoElement}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_H_ diff --git a/bridge/include/plugin_api/transition_event_init.h b/bridge/include/plugin_api/transition_event_init.h new file mode 100644 index 0000000000..f208c1cde6 --- /dev/null +++ b/bridge/include/plugin_api/transition_event_init.h @@ -0,0 +1,21 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +struct WebFTransitionEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + double elapsed_time; + const char* property_name; + const char* pseudo_element; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_TRANSITION_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/ui_event.h b/bridge/include/plugin_api/ui_event.h new file mode 100644 index 0000000000..9e15ef08c2 --- /dev/null +++ b/bridge/include/plugin_api/ui_event.h @@ -0,0 +1,33 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_H_ +#include +#include "script_value_ref.h" +#include "event.h" +namespace webf { +class Window; +typedef struct WindowPublicMethods WindowPublicMethods; +class SharedExceptionState; +class ExecutingContext; +class UIEvent; +typedef struct ScriptValueRef ScriptValueRef; +using PublicUIEventGetDetail = double (*)(UIEvent*); +using PublicUIEventGetView = WebFValue (*)(UIEvent*); +using PublicUIEventGetWhich = double (*)(UIEvent*); +struct UIEventPublicMethods : public WebFPublicMethods { + static double Detail(UIEvent* ui_event); + static WebFValue View(UIEvent* ui_event); + static double Which(UIEvent* ui_event); + double version{1.0}; + EventPublicMethods event; + PublicUIEventGetDetail ui_event_get_detail{Detail}; + PublicUIEventGetView ui_event_get_view{View}; + PublicUIEventGetWhich ui_event_get_which{Which}; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_H_ diff --git a/bridge/include/plugin_api/ui_event_init.h b/bridge/include/plugin_api/ui_event_init.h new file mode 100644 index 0000000000..5e3c7393ab --- /dev/null +++ b/bridge/include/plugin_api/ui_event_init.h @@ -0,0 +1,23 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ +#ifndef WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_INIT_H_ +#define WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_INIT_H_ +#include +#include "webf_value.h" +namespace webf { +typedef struct Window Window; +typedef struct WindowPublicMethods WindowPublicMethods; +struct WebFUIEventInit { + int32_t bubbles; + int32_t cancelable; + int32_t composed; + double detail; + WebFValue view; + double which; +}; +} // namespace webf +#endif // WEBF_CORE_WEBF_API_PLUGIN_API_UI_EVENT_INIT_H_ diff --git a/bridge/include/plugin_api/webf_value.h b/bridge/include/plugin_api/webf_value.h new file mode 100644 index 0000000000..4c37912e90 --- /dev/null +++ b/bridge/include/plugin_api/webf_value.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_WEBF_API_WEBF_VALUE_H_ +#define WEBF_CORE_WEBF_API_WEBF_VALUE_H_ + +#include "rust_readable.h" + +namespace webf { + +/// A simple, long-lived struct to check if the underlying pointer of WebFValue has been disposed +struct WebFValueStatus : public RustReadable { + bool disposed = false; +}; + +template +/// Simple struct value both contains the value returned to external native plugin and related C function pointers. +struct WebFValue { + WebFValue() = delete; + static WebFValue Null() { return WebFValue(nullptr, nullptr, nullptr); } + explicit WebFValue(T* value, const U* method, WebFValueStatus* status) + : value(value), method_pointer(method), status(status){}; + T* value; + const U* method_pointer; + WebFValueStatus* status; +}; + +// Memory aligned and readable from external C/C++/Rust side. +// Only C type member can be included in this class, any C++ type and classes can is not allowed to use here. +struct WebFPublicMethods : RustReadable {}; + +template +WebFValue ToWebFValue(void* value, void* method_pointer) { + return {.value = value, .method_pointer = method_pointer}; +} + +} // namespace webf + +#endif // WEBF_CORE_WEBF_API_WEBF_VALUE_H_ diff --git a/bridge/include/plugin_api/window.h b/bridge/include/plugin_api/window.h new file mode 100644 index 0000000000..83743a44c1 --- /dev/null +++ b/bridge/include/plugin_api/window.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_RUST_API_WINDOW_H_ +#define WEBF_CORE_RUST_API_WINDOW_H_ + +#include "event_target.h" + +namespace webf { + +class EventTarget; +class SharedExceptionState; +class ExecutingContext; +class Event; + +struct WindowPublicMethods : WebFPublicMethods { + double version{1.0}; + EventTargetPublicMethods event_target; +}; + +} // namespace webf + +#endif // WEBF_CORE_RUST_API_WINDOW_H_ diff --git a/bridge/include/webf_bridge.h b/bridge/include/webf_bridge.h index 6163a28afd..2900e42ec5 100644 --- a/bridge/include/webf_bridge.h +++ b/bridge/include/webf_bridge.h @@ -18,10 +18,10 @@ #define WEBF_EXPORT __attribute__((__visibility__("default"))) #endif -typedef struct SharedNativeString SharedNativeString; -typedef struct NativeValue NativeValue; -typedef struct NativeScreen NativeScreen; -typedef struct NativeByteCode NativeByteCode; +class SharedNativeString; +class NativeValue; +class NativeScreen; +class NativeByteCode; struct WebFInfo { const char* app_name{nullptr}; diff --git a/bridge/multiple_threading/dispatcher.cc b/bridge/multiple_threading/dispatcher.cc index 55b5914093..54bfd5fe40 100644 --- a/bridge/multiple_threading/dispatcher.cc +++ b/bridge/multiple_threading/dispatcher.cc @@ -140,7 +140,7 @@ bool Dispatcher::NotifyDart(const DartWork* work_ptr, bool is_sync) { } void Dispatcher::FinalizeAllJSThreads(webf::multi_threading::Callback callback) { - std::atomic unfinished_thread = js_threads_.size(); + std::atomic unfinished_thread = js_threads_.size(); std::atomic is_final_async_dart_task_complete{false}; diff --git a/bridge/multiple_threading/dispatcher.h b/bridge/multiple_threading/dispatcher.h index 13c819de35..10d1bdc00a 100644 --- a/bridge/multiple_threading/dispatcher.h +++ b/bridge/multiple_threading/dispatcher.h @@ -55,11 +55,13 @@ class Dispatcher { return; } +#if FLUTTER_BACKEND auto task = std::make_shared>(std::forward(func), std::forward(args)...); DartWork work = [task](bool cancel) { (*task)(); }; const DartWork* work_ptr = new DartWork(work); NotifyDart(work_ptr, false); +#endif } template diff --git a/bridge/polyfill/src/dom.ts b/bridge/polyfill/src/dom.ts index 93a39251af..0fa9394a80 100644 --- a/bridge/polyfill/src/dom.ts +++ b/bridge/polyfill/src/dom.ts @@ -12,6 +12,7 @@ document.documentElement.appendChild(head); let body = document.createElement('body'); document.documentElement.appendChild(body); + // SVGMatrix are equal to DOMMatrix. Object.defineProperty(window, 'SVGMatrix', { value: DOMMatrix diff --git a/bridge/rusty_webf_sys/.gitignore b/bridge/rusty_webf_sys/.gitignore new file mode 100644 index 0000000000..f81aa21ffb --- /dev/null +++ b/bridge/rusty_webf_sys/.gitignore @@ -0,0 +1,3 @@ +./include +target +Cargo.lock \ No newline at end of file diff --git a/bridge/rusty_webf_sys/Cargo.toml b/bridge/rusty_webf_sys/Cargo.toml new file mode 100644 index 0000000000..4fe851bce0 --- /dev/null +++ b/bridge/rusty_webf_sys/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "webf-sys" +version = "0.16.0" +edition = "2021" +repository = "https://github.com/openwebf/webf" +homepage = "https://openwebf.com" +description = "Rust bindings to Web API which provided by WebF" +license = "Apache-2.0" +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libc = "0.2.0" + + +[dependencies.windows] +version = "0.58.0" +features = [ + "Win32_System_Memory" +] \ No newline at end of file diff --git a/bridge/rusty_webf_sys/README.md b/bridge/rusty_webf_sys/README.md new file mode 100644 index 0000000000..bccb80bfc5 --- /dev/null +++ b/bridge/rusty_webf_sys/README.md @@ -0,0 +1,10 @@ +WebF Binding for Rust +====================== + +A high-performance binding library enables Rust developers to access WebF's DOM & Web API directly through Rust to C +FFI. + +This library provides native-speed DOM and Web API access through WebF — a web browser-compatible rendering engine built +atop Flutter. It enables the creation of native-speed Flutter apps using HTML/CSS and Rust, allowing your Rust for Web +apps to run in Flutter with performance up to 3x faster than in a web browser. + diff --git a/bridge/rusty_webf_sys/src/add_event_listener_options.rs b/bridge/rusty_webf_sys/src/add_event_listener_options.rs new file mode 100644 index 0000000000..7196c60be2 --- /dev/null +++ b/bridge/rusty_webf_sys/src/add_event_listener_options.rs @@ -0,0 +1,13 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct AddEventListenerOptions { + pub capture: i32, + pub passive: i32, + pub once: i32, +} diff --git a/bridge/rusty_webf_sys/src/animation_event.rs b/bridge/rusty_webf_sys/src/animation_event.rs new file mode 100644 index 0000000000..7a802bdab8 --- /dev/null +++ b/bridge/rusty_webf_sys/src/animation_event.rs @@ -0,0 +1,130 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct AnimationEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub animation_name: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub elapsed_time: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub pseudo_element: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, +} +pub struct AnimationEvent { + pub event: Event, + method_pointer: *const AnimationEventRustMethods, +} +impl AnimationEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const AnimationEventRustMethods, status: *const RustValueStatus) -> AnimationEvent { + unsafe { + AnimationEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn animation_name(&self) -> String { + let value = unsafe { + ((*self.method_pointer).animation_name)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn elapsed_time(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).elapsed_time)(self.ptr()) + }; + value + } + pub fn pseudo_element(&self) -> String { + let value = unsafe { + ((*self.method_pointer).pseudo_element)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } +} +pub trait AnimationEventMethods: EventMethods { + fn animation_name(&self) -> String; + fn elapsed_time(&self) -> f64; + fn pseudo_element(&self) -> String; + fn as_animation_event(&self) -> &AnimationEvent; +} +impl AnimationEventMethods for AnimationEvent { + fn animation_name(&self) -> String { + self.animation_name() + } + fn elapsed_time(&self) -> f64 { + self.elapsed_time() + } + fn pseudo_element(&self) -> String { + self.pseudo_element() + } + fn as_animation_event(&self) -> &AnimationEvent { + self + } +} +impl EventMethods for AnimationEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/animation_event_init.rs b/bridge/rusty_webf_sys/src/animation_event_init.rs new file mode 100644 index 0000000000..41fc67c884 --- /dev/null +++ b/bridge/rusty_webf_sys/src/animation_event_init.rs @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct AnimationEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub animation_name: *const c_char, + pub elapsed_time: c_double, + pub pseudo_element: *const c_char, +} diff --git a/bridge/rusty_webf_sys/src/character_data.rs b/bridge/rusty_webf_sys/src/character_data.rs new file mode 100644 index 0000000000..de26e9fa28 --- /dev/null +++ b/bridge/rusty_webf_sys/src/character_data.rs @@ -0,0 +1,55 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct CharacterDataRustMethods { + pub version: c_double, + pub node: NodeRustMethods, +} + +impl RustMethods for CharacterDataRustMethods {} + +pub struct CharacterData { + pub node: Node, + method_pointer: *const CharacterDataRustMethods, +} + +impl CharacterData {} + +impl EventTargetMethods for CharacterData { + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + CharacterData { + node: Node::initialize(ptr, context, &(method_pointer as *const CharacterDataRustMethods).as_ref().unwrap().node, status), + method_pointer: method_pointer as *const CharacterDataRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.node.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.node.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.node.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.node.dispatch_event(event, exception_state) + } +} diff --git a/bridge/rusty_webf_sys/src/close_event.rs b/bridge/rusty_webf_sys/src/close_event.rs new file mode 100644 index 0000000000..88deb07432 --- /dev/null +++ b/bridge/rusty_webf_sys/src/close_event.rs @@ -0,0 +1,129 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct CloseEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub code: extern "C" fn(ptr: *const OpaquePtr) -> i64, + pub reason: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub was_clean: extern "C" fn(ptr: *const OpaquePtr) -> i32, +} +pub struct CloseEvent { + pub event: Event, + method_pointer: *const CloseEventRustMethods, +} +impl CloseEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const CloseEventRustMethods, status: *const RustValueStatus) -> CloseEvent { + unsafe { + CloseEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn code(&self) -> i64 { + let value = unsafe { + ((*self.method_pointer).code)(self.ptr()) + }; + value + } + pub fn reason(&self) -> String { + let value = unsafe { + ((*self.method_pointer).reason)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn was_clean(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).was_clean)(self.ptr()) + }; + value != 0 + } +} +pub trait CloseEventMethods: EventMethods { + fn code(&self) -> i64; + fn reason(&self) -> String; + fn was_clean(&self) -> bool; + fn as_close_event(&self) -> &CloseEvent; +} +impl CloseEventMethods for CloseEvent { + fn code(&self) -> i64 { + self.code() + } + fn reason(&self) -> String { + self.reason() + } + fn was_clean(&self) -> bool { + self.was_clean() + } + fn as_close_event(&self) -> &CloseEvent { + self + } +} +impl EventMethods for CloseEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/close_event_init.rs b/bridge/rusty_webf_sys/src/close_event_init.rs new file mode 100644 index 0000000000..998cbec348 --- /dev/null +++ b/bridge/rusty_webf_sys/src/close_event_init.rs @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct CloseEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub code: i64, + pub reason: *const c_char, + pub was_clean: i32, +} diff --git a/bridge/rusty_webf_sys/src/comment.rs b/bridge/rusty_webf_sys/src/comment.rs new file mode 100644 index 0000000000..1c845fe3b5 --- /dev/null +++ b/bridge/rusty_webf_sys/src/comment.rs @@ -0,0 +1,56 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct CommentRustMethods { + pub version: c_double, + pub character_data: CharacterDataRustMethods, +} + +impl RustMethods for CommentRustMethods {} + +pub struct Comment { + pub character_data: CharacterData, + method_pointer: *const CommentRustMethods, +} + +impl Comment {} + +impl EventTargetMethods for Comment { + /// Initialize the instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + Comment { + character_data: CharacterData::initialize(ptr, context, &(method_pointer as *const CommentRustMethods).as_ref().unwrap().character_data, status), + method_pointer: method_pointer as *const CommentRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.character_data.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.character_data.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.character_data.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.character_data.dispatch_event(event, exception_state) + } +} diff --git a/bridge/rusty_webf_sys/src/container_node.rs b/bridge/rusty_webf_sys/src/container_node.rs new file mode 100644 index 0000000000..0050bead99 --- /dev/null +++ b/bridge/rusty_webf_sys/src/container_node.rs @@ -0,0 +1,77 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct ContainerNodeRustMethods { + pub version: c_double, + pub node: NodeRustMethods, +} + +impl RustMethods for ContainerNodeRustMethods {} + +pub struct ContainerNode { + pub node: Node, + method_pointer: *const ContainerNodeRustMethods, +} + +impl ContainerNode { + +} + +pub trait ContainerNodeMethods : NodeMethods { +} + +impl NodeMethods for ContainerNode { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.node.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.node.remove_child(target_node, exception_state) + } + + fn as_node(&self) -> &Node { + &self.node + } +} + +impl EventTargetMethods for ContainerNode { + /// Initialize the instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + ContainerNode { + node: Node::initialize(ptr, context, &(method_pointer as *const ContainerNodeRustMethods).as_ref().unwrap().node, status), + method_pointer: method_pointer as *const ContainerNodeRustMethods + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.node.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.node.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.node.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.node.dispatch_event(event, exception_state) + } +} + +impl ContainerNodeMethods for ContainerNode {} diff --git a/bridge/rusty_webf_sys/src/custom_event.rs b/bridge/rusty_webf_sys/src/custom_event.rs new file mode 100644 index 0000000000..f8f284c7b8 --- /dev/null +++ b/bridge/rusty_webf_sys/src/custom_event.rs @@ -0,0 +1,123 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct CustomEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub detail: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, + pub init_custom_event: extern "C" fn(ptr: *const OpaquePtr, *const c_char, i32, i32, *const OpaquePtr, exception_state: *const OpaquePtr) -> c_void, +} +pub struct CustomEvent { + pub event: Event, + method_pointer: *const CustomEventRustMethods, +} +impl CustomEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const CustomEventRustMethods, status: *const RustValueStatus) -> CustomEvent { + unsafe { + CustomEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn detail(&self) -> ScriptValueRef { + let value = unsafe { + ((*self.method_pointer).detail)(self.ptr()) + }; + ScriptValueRef { + ptr: value.value, + method_pointer: value.method_pointer + } + } + pub fn init_custom_event(&self, type_: &str, canBubble: bool, cancelable: bool, detail: &ScriptValueRef, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).init_custom_event)(self.ptr(), CString::new(type_).unwrap().as_ptr(), i32::from(canBubble), i32::from(cancelable), detail.ptr, exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } +} +pub trait CustomEventMethods: EventMethods { + fn detail(&self) -> ScriptValueRef; + fn init_custom_event(&self, type_: &str, canBubble: bool, cancelable: bool, detail: &ScriptValueRef, exception_state: &ExceptionState) -> Result<(), String>; + fn as_custom_event(&self) -> &CustomEvent; +} +impl CustomEventMethods for CustomEvent { + fn detail(&self) -> ScriptValueRef { + self.detail() + } + fn init_custom_event(&self, type_: &str, canBubble: bool, cancelable: bool, detail: &ScriptValueRef, exception_state: &ExceptionState) -> Result<(), String> { + self.init_custom_event(type_, canBubble, cancelable, detail, exception_state) + } + fn as_custom_event(&self) -> &CustomEvent { + self + } +} +impl EventMethods for CustomEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/document.rs b/bridge/rusty_webf_sys/src/document.rs new file mode 100644 index 0000000000..6fee1559f4 --- /dev/null +++ b/bridge/rusty_webf_sys/src/document.rs @@ -0,0 +1,326 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct ElementCreationOptions { + pub is: *const c_char, +} + +#[repr(C)] +pub struct DocumentRustMethods { + pub version: c_double, + pub container_node: ContainerNodeRustMethods, + pub create_element: extern "C" fn(document: *const OpaquePtr, tag_name: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub create_element_with_element_creation_options: extern "C" fn( + document: *const OpaquePtr, + tag_name: *const c_char, + options: &mut ElementCreationOptions, + exception_state: *const OpaquePtr) -> RustValue, + pub create_element_ns: extern "C" fn(document: *const OpaquePtr, uri: *const c_char, tag_name: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub create_element_ns_with_element_creation_options: extern "C" fn( + document: *const OpaquePtr, + uri: *const c_char, + tag_name: *const c_char, + options: &mut ElementCreationOptions, + exception_state: *const OpaquePtr) -> RustValue, + pub create_text_node: extern "C" fn(document: *const OpaquePtr, data: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub create_document_fragment: extern "C" fn(document: *const OpaquePtr, exception_state: *const OpaquePtr) -> RustValue, + pub create_comment: extern "C" fn(document: *const OpaquePtr, data: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub create_event: extern "C" fn(document: *const OpaquePtr, event_type: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub query_selector: extern "C" fn(document: *const OpaquePtr, selectors: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub get_element_by_id: extern "C" fn(document: *const OpaquePtr, element_id: *const c_char, exception_state: *const OpaquePtr) -> RustValue, + pub element_from_point: extern "C" fn(document: *const OpaquePtr, x: c_double, y: c_double, exception_state: *const OpaquePtr) -> RustValue, + pub document_element: extern "C" fn(document: *const OpaquePtr) -> RustValue, + pub head: extern "C" fn(document: *const OpaquePtr) -> RustValue, + pub body: extern "C" fn(document: *const OpaquePtr) -> RustValue, +} + +impl RustMethods for DocumentRustMethods {} + +pub struct Document { + pub container_node: ContainerNode, + method_pointer: *const DocumentRustMethods, +} + +impl Document { + /// Behavior as same as `document.createElement()` in JavaScript. + /// the createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized. + pub fn create_element(&self, name: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let name_c_string = CString::new(name).unwrap(); + let new_element_value = unsafe { + ((*self.method_pointer).create_element)(event_target.ptr, name_c_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(new_element_value.value, event_target.context(), new_element_value.method_pointer, new_element_value.status)); + } + + pub fn create_element_with_element_creation_options(&self, name: &str, options: &mut ElementCreationOptions, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let name_c_string = CString::new(name).unwrap(); + let new_element_value = unsafe { + ((*self.method_pointer).create_element_with_element_creation_options)(event_target.ptr, name_c_string.as_ptr(), options, exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(new_element_value.value, event_target.context(), new_element_value.method_pointer, new_element_value.status)); + } + + pub fn create_element_with_str(&self, name: &str, str_options: &CString, exception_state: &ExceptionState) -> Result { + let options = &mut ElementCreationOptions { + is: str_options.as_ptr(), + }; + return self.create_element_with_element_creation_options(name, options, exception_state); + } + + /// Behavior as same as `document.createElementNS()` in JavaScript. + /// Creates a new element with the given namespace URI and qualified name. + /// The qualified name is a concatenation of the namespace prefix, a colon, and the local name. + pub fn create_element_ns(&self, uri: &CString, name: &CString, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let new_element_value = unsafe { + ((*self.method_pointer).create_element_ns)(event_target.ptr, uri.as_ptr(), name.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(new_element_value.value, event_target.context(), new_element_value.method_pointer, new_element_value.status)); + } + + pub fn create_element_ns_with_element_creation_options(&self, uri: &str, name: &str, options: &mut ElementCreationOptions, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let uri_c_string = CString::new(uri).unwrap(); + let name_c_string = CString::new(name).unwrap(); + let new_element_value = unsafe { + ((*self.method_pointer).create_element_ns_with_element_creation_options)(event_target.ptr, uri_c_string.as_ptr(), name_c_string.as_ptr(), options, exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(new_element_value.value, event_target.context(), new_element_value.method_pointer, new_element_value.status)); + } + + pub fn create_element_ns_with_str(&self, uri: &str, name: &str, str_options: &CString, exception_state: &ExceptionState) -> Result { + let options = &mut ElementCreationOptions { + is: str_options.as_ptr(), + }; + return self.create_element_ns_with_element_creation_options(uri, name, options, exception_state); + } + + /// Behavior as same as `document.createTextNode()` in JavaScript. + /// Creates a new Text node. This method can be used to escape HTML characters. + pub fn create_text_node(&self, data: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let data_c_string = CString::new(data).unwrap(); + let new_text_node = unsafe { + ((*self.method_pointer).create_text_node)(event_target.ptr, data_c_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Text::initialize(new_text_node.value, event_target.context(), new_text_node.method_pointer, new_text_node.status)); + } + + /// Behavior as same as `document.createDocumentFragment()` in JavaScript. + /// Creates a new DocumentFragment. + pub fn create_document_fragment(&self, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let new_document_fragment = unsafe { + ((*self.method_pointer).create_document_fragment)(event_target.ptr, exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(DocumentFragment::initialize(new_document_fragment.value, event_target.context(), new_document_fragment.method_pointer, new_document_fragment.status)); + } + + /// Behavior as same as `document.createComment()` in JavaScript. + /// Creates a new Comment node with the given data. + pub fn create_comment(&self, data: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let data_c_string = CString::new(data).unwrap(); + let new_comment = unsafe { + ((*self.method_pointer).create_comment)(event_target.ptr, data_c_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Comment::initialize(new_comment.value, event_target.context(), new_comment.method_pointer, new_comment.status)); + } + + /// Behavior as same as `document.createEvent()` in JavaScript. + /// Creates a new event of the type specified. + pub fn create_event(&self, event_type: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let event_type_c_string = CString::new(event_type).unwrap(); + let new_event = unsafe { + ((*self.method_pointer).create_event)(event_target.ptr, event_type_c_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Event::initialize(new_event.value, event_target.context(), new_event.method_pointer, new_event.status)); + } + + /// Behavior as same as `document.querySelector()` in JavaScript. + /// Returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. + pub fn query_selector(&self, selectors: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let selectoc_string = CString::new(selectors).unwrap(); + let element_value = unsafe { + ((*self.method_pointer).query_selector)(event_target.ptr, selectoc_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(element_value.value, event_target.context(), element_value.method_pointer, element_value.status)); + } + + /// Behavior as same as `document.getElementById()` in JavaScript. + /// Returns a reference to the element by its ID. + pub fn get_element_by_id(&self, element_id: &str, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let id_c_string = CString::new(element_id).unwrap(); + let element_value = unsafe { + ((*self.method_pointer).get_element_by_id)(event_target.ptr, id_c_string.as_ptr(), exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(element_value.value, event_target.context(), element_value.method_pointer, element_value.status)); + } + + /// Behavior as same as `document.elementFromPoint()` in JavaScript. + /// Returns the element from the document whose elementFromPoint() method is being called which is the topmost element which lies under the given point. + pub fn element_from_point(&self, x: f64, y: f64, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.container_node.node.event_target; + let element_value = unsafe { + ((*self.method_pointer).element_from_point)(event_target.ptr, x, y, exception_state.ptr) + }; + + if exception_state.has_exception() { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Element::initialize(element_value.value, event_target.context(), element_value.method_pointer, element_value.status)); + } + + /// Document.documentElement returns the Element that is the root element of the document + /// (for example, the element for HTML documents). + pub fn document_element(&self) -> HTMLElement { + let event_target: &EventTarget = &self.container_node.node.event_target; + let html_element_value = unsafe { + ((*self.method_pointer).document_element)(event_target.ptr) + }; + + return HTMLElement::initialize(html_element_value.value, event_target.context(), html_element_value.method_pointer, html_element_value.status); + } + + /// The Document.head property represents the or of the current document, + /// or null if no such element exists. + pub fn head(&self) -> HTMLElement { + let event_target: &EventTarget = &self.container_node.node.event_target; + let head_element_value = unsafe { + ((*self.method_pointer).head)(event_target.ptr) + }; + return HTMLElement::initialize(head_element_value.value, event_target.context(), head_element_value.method_pointer, head_element_value.status); + } + + + /// The Document.body property represents the or of the current document, + /// or null if no such element exists. + pub fn body(&self) -> HTMLElement { + let event_target: &EventTarget = &self.container_node.node.event_target; + let body_element_value = unsafe { + ((*self.method_pointer).body)(event_target.ptr) + }; + return HTMLElement::initialize(body_element_value.value, event_target.context(), body_element_value.method_pointer, body_element_value.status); + } +} + +trait DocumentMethods: ContainerNodeMethods {} + +impl NodeMethods for Document { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.remove_child(target_node, exception_state) + } + + fn as_node(&self) -> &Node { + &self.container_node.node + } +} + +impl EventTargetMethods for Document { + /// Initialize the document instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + Document { + container_node: ContainerNode::initialize( + ptr, + context, + &(method_pointer as *const DocumentRustMethods).as_ref().unwrap().container_node, + status, + ), + method_pointer: method_pointer as *const DocumentRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.container_node.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.node.event_target.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.node.event_target.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.container_node.node.event_target.dispatch_event(event, exception_state) + } +} + +impl ContainerNodeMethods for Document {} + +impl DocumentMethods for Document {} diff --git a/bridge/rusty_webf_sys/src/document_fragment.rs b/bridge/rusty_webf_sys/src/document_fragment.rs new file mode 100644 index 0000000000..87a725af8e --- /dev/null +++ b/bridge/rusty_webf_sys/src/document_fragment.rs @@ -0,0 +1,81 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct DocumentFragmentRustMethods { + pub version: c_double, + pub container_node: ContainerNodeRustMethods, +} + +impl RustMethods for DocumentFragmentRustMethods {} + +pub struct DocumentFragment { + container_node: ContainerNode, + method_pointer: *const DocumentFragmentRustMethods, +} + +impl DocumentFragment {} + +pub trait DocumentFragmentMethods: ContainerNodeMethods {} + +impl ContainerNodeMethods for DocumentFragment {} + +impl NodeMethods for DocumentFragment { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.remove_child(target_node, exception_state) + } + + + fn as_node(&self) -> &Node { + &self.container_node.node + } +} + +impl EventTargetMethods for DocumentFragment { + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + DocumentFragment { + container_node: ContainerNode::initialize( + ptr, + context, + &(method_pointer as *const DocumentFragmentRustMethods).as_ref().unwrap().container_node, + status, + ), + method_pointer: method_pointer as *const DocumentFragmentRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.container_node.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.container_node.dispatch_event(event, exception_state) + } +} + +impl DocumentFragmentMethods for DocumentFragment {} diff --git a/bridge/rusty_webf_sys/src/element.rs b/bridge/rusty_webf_sys/src/element.rs new file mode 100644 index 0000000000..cb42d9c152 --- /dev/null +++ b/bridge/rusty_webf_sys/src/element.rs @@ -0,0 +1,100 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct ElementRustMethods { + pub version: c_double, + pub container_node: ContainerNodeRustMethods, +} + +impl RustMethods for ElementRustMethods {} + +#[repr(C)] +enum ElementType { + kHTMLDIVElement, + kHTMLAnchorElement, + kHTMLHeadElement, + kHTMLBodyElement, + kHTMLHTMLElement, + kHTMLImageElement, + kHTMLLinkElement, + kHTMLScriptElement, + kHTMLTemplateElement, + kHTMLUnknownElement, + kHTMLCanvasElement, + kHTMLWidgetElement, + kHTMLButtonElement, + kHTMLFormElement, + kHTMLInputElement, + kHTMLTextAreaElement +} + +pub struct Element { + container_node: ContainerNode, + method_pointer: *const ElementRustMethods, +} + +impl Element {} + +pub trait ElementMethods: ContainerNodeMethods {} + +impl ContainerNodeMethods for Element {} + +impl NodeMethods for Element { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.container_node.node.remove_child(target_node, exception_state) + } + + fn as_node(&self) -> &Node { + &self.container_node.node + } +} + +impl EventTargetMethods for Element { + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + Element { + container_node: ContainerNode::initialize( + ptr, + context, + &(method_pointer as *const ElementRustMethods).as_ref().unwrap().container_node, + status + ), + method_pointer: method_pointer as *const ElementRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.container_node.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.container_node.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.container_node.dispatch_event(event, exception_state) + } +} + +impl ElementMethods for Element {} diff --git a/bridge/rusty_webf_sys/src/event.rs b/bridge/rusty_webf_sys/src/event.rs new file mode 100644 index 0000000000..dcc812a8bb --- /dev/null +++ b/bridge/rusty_webf_sys/src/event.rs @@ -0,0 +1,231 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct EventRustMethods { + pub version: c_double, + pub bubbles: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub cancel_bubble: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub set_cancel_bubble: extern "C" fn(ptr: *const OpaquePtr, value: i32, exception_state: *const OpaquePtr) -> bool, + pub cancelable: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub current_target: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, + pub default_prevented: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub src_element: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, + pub target: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, + pub is_trusted: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub time_stamp: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub type_: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub init_event: extern "C" fn(ptr: *const OpaquePtr, *const c_char, i32, i32, exception_state: *const OpaquePtr) -> c_void, + pub prevent_default: extern "C" fn(ptr: *const OpaquePtr, exception_state: *const OpaquePtr) -> c_void, + pub stop_immediate_propagation: extern "C" fn(ptr: *const OpaquePtr, exception_state: *const OpaquePtr) -> c_void, + pub stop_propagation: extern "C" fn(ptr: *const OpaquePtr, exception_state: *const OpaquePtr) -> c_void, + pub release: extern "C" fn(ptr: *const OpaquePtr) -> c_void, +} +pub struct Event { + pub ptr: *const OpaquePtr, + context: *const ExecutingContext, + method_pointer: *const EventRustMethods, + status: *const RustValueStatus +} +impl Event { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const EventRustMethods, status: *const RustValueStatus) -> Event { + Event { + ptr, + context, + method_pointer, + status + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.ptr + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + assert!(!self.context.is_null(), "Context PTR must not be null"); + unsafe { &*self.context } + } + pub fn bubbles(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).bubbles)(self.ptr()) + }; + value != 0 + } + pub fn cancel_bubble(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).cancel_bubble)(self.ptr()) + }; + value != 0 + } + pub fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).set_cancel_bubble)(self.ptr(), i32::from(value), exception_state.ptr) + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + pub fn cancelable(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).cancelable)(self.ptr()) + }; + value != 0 + } + pub fn current_target(&self) -> EventTarget { + let value = unsafe { + ((*self.method_pointer).current_target)(self.ptr()) + }; + EventTarget::initialize(value.value, self.context(), value.method_pointer, value.status) + } + pub fn default_prevented(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).default_prevented)(self.ptr()) + }; + value != 0 + } + pub fn src_element(&self) -> EventTarget { + let value = unsafe { + ((*self.method_pointer).src_element)(self.ptr()) + }; + EventTarget::initialize(value.value, self.context(), value.method_pointer, value.status) + } + pub fn target(&self) -> EventTarget { + let value = unsafe { + ((*self.method_pointer).target)(self.ptr()) + }; + EventTarget::initialize(value.value, self.context(), value.method_pointer, value.status) + } + pub fn is_trusted(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).is_trusted)(self.ptr()) + }; + value != 0 + } + pub fn time_stamp(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).time_stamp)(self.ptr()) + }; + value + } + pub fn type_(&self) -> String { + let value = unsafe { + ((*self.method_pointer).type_)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).init_event)(self.ptr(), CString::new(type_).unwrap().as_ptr(), i32::from(bubbles), i32::from(cancelable), exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + pub fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).prevent_default)(self.ptr(), exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + pub fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).stop_immediate_propagation)(self.ptr(), exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + pub fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).stop_propagation)(self.ptr(), exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } +} +impl Drop for Event { + fn drop(&mut self) { + unsafe { + ((*self.method_pointer).release)(self.ptr()); + } + } +} +pub trait EventMethods { + fn bubbles(&self) -> bool; + fn cancel_bubble(&self) -> bool; + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String>; + fn cancelable(&self) -> bool; + fn current_target(&self) -> EventTarget; + fn default_prevented(&self) -> bool; + fn src_element(&self) -> EventTarget; + fn target(&self) -> EventTarget; + fn is_trusted(&self) -> bool; + fn time_stamp(&self) -> f64; + fn type_(&self) -> String; + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String>; + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String>; + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String>; + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String>; + fn as_event(&self) -> &Event; +} +impl EventMethods for Event { + fn bubbles(&self) -> bool { + self.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.cancelable() + } + fn current_target(&self) -> EventTarget { + self.current_target() + } + fn default_prevented(&self) -> bool { + self.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.src_element() + } + fn target(&self) -> EventTarget { + self.target() + } + fn is_trusted(&self) -> bool { + self.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.time_stamp() + } + fn type_(&self) -> String { + self.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + self + } +} diff --git a/bridge/rusty_webf_sys/src/event_init.rs b/bridge/rusty_webf_sys/src/event_init.rs new file mode 100644 index 0000000000..07ce0f7bc5 --- /dev/null +++ b/bridge/rusty_webf_sys/src/event_init.rs @@ -0,0 +1,13 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct EventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, +} diff --git a/bridge/rusty_webf_sys/src/event_listener_options.rs b/bridge/rusty_webf_sys/src/event_listener_options.rs new file mode 100644 index 0000000000..f5fc1a4152 --- /dev/null +++ b/bridge/rusty_webf_sys/src/event_listener_options.rs @@ -0,0 +1,11 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct EventListenerOptions { + pub capture: i32, +} diff --git a/bridge/rusty_webf_sys/src/event_target.rs b/bridge/rusty_webf_sys/src/event_target.rs new file mode 100644 index 0000000000..f940ef7623 --- /dev/null +++ b/bridge/rusty_webf_sys/src/event_target.rs @@ -0,0 +1,343 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::{c_double, c_void, CString, c_char}; +use crate::add_event_listener_options::AddEventListenerOptions; +use crate::element::{Element, ElementRustMethods}; +use crate::event::{Event, EventRustMethods}; +use crate::exception_state::ExceptionState; +use crate::executing_context::{ExecutingContext, ExecutingContextRustMethods}; +use crate::{executing_context, OpaquePtr, RustValue, RustValueStatus}; +use crate::container_node::{ContainerNode, ContainerNodeRustMethods}; +use crate::document::{Document, DocumentRustMethods}; +use crate::html_element::{HTMLElement, HTMLElementRustMethods}; +use crate::node::{Node, NodeRustMethods}; +use crate::window::{Window, WindowRustMethods}; + +#[repr(C)] +struct EventCallbackContext { + pub callback: extern "C" fn(event_callback_context: *const OpaquePtr, + event: *const OpaquePtr, + event_method_pointer: *const EventRustMethods, + status: *const RustValueStatus, + exception_state: *const OpaquePtr) -> *const c_void, + pub free_ptr: extern "C" fn(event_callback_context_ptr: *const OpaquePtr) -> *const c_void, + pub ptr: *const EventCallbackContextData, +} + +struct EventCallbackContextData { + executing_context_ptr: *const OpaquePtr, + executing_context_method_pointer: *const ExecutingContextRustMethods, + func: EventListenerCallback, +} + +impl Drop for EventCallbackContextData { + fn drop(&mut self) { + println!("Drop event callback context data"); + } +} + +pub trait RustMethods {} + + +#[repr(C)] +enum EventTargetType { + EventTarget = 0, + Node = 1, + ContainerNode = 2, + Window = 3, + Document = 4, + Element = 5, + HTMLElement = 6, + HTMLImageElement = 7, + HTMLCanvasElement = 8, + HTMLDivElement = 9, + HTMLScriptElement = 10, + DocumentFragment = 11, + Text = 12, + Comment = 13, +} + +#[repr(C)] +pub struct EventTargetRustMethods { + pub version: c_double, + pub add_event_listener: extern "C" fn( + event_target: *const OpaquePtr, + event_name: *const c_char, + callback_context: *const EventCallbackContext, + options: *const AddEventListenerOptions, + exception_state: *const OpaquePtr) -> c_void, + pub remove_event_listener: extern "C" fn( + event_target: *const OpaquePtr, + event_name: *const c_char, + callback_context: *const EventCallbackContext, + exception_state: *const OpaquePtr) -> c_void, + pub dispatch_event: extern "C" fn( + event_target: *const OpaquePtr, + event: *const OpaquePtr, + exception_state: *const OpaquePtr) -> bool, + pub release: extern "C" fn(event_target: *const OpaquePtr), + pub dynamic_to: extern "C" fn(event_target: *const OpaquePtr, event_target_type: EventTargetType) -> RustValue, +} + +impl RustMethods for EventTargetRustMethods {} + + +pub struct EventTarget { + pub ptr: *const OpaquePtr, + status: *const RustValueStatus, + context: *const ExecutingContext, + method_pointer: *const EventTargetRustMethods, +} + +pub type EventListenerCallback = Box; + +// Define the callback function +extern "C" fn handle_event_listener_callback( + event_callback_context_ptr: *const OpaquePtr, + event_ptr: *const OpaquePtr, + event_method_pointer: *const EventRustMethods, + status: *const RustValueStatus, + exception_state: *const OpaquePtr, +) -> *const c_void { + // Reconstruct the Box and drop it to free the memory + let event_callback_context = unsafe { + &(*(event_callback_context_ptr as *mut EventCallbackContext)) + }; + let callback_context_data = unsafe { + &(*(event_callback_context.ptr as *mut EventCallbackContextData)) + }; + + unsafe { + let func = &(*callback_context_data).func; + let callback_data = &(*callback_context_data); + let executing_context = ExecutingContext::initialize(callback_data.executing_context_ptr, callback_data.executing_context_method_pointer); + let event = Event::initialize(event_ptr, &executing_context, event_method_pointer, status); + func(&event); + } + + std::ptr::null() +} + +extern "C" fn handle_callback_data_free(event_callback_context_ptr: *const OpaquePtr) -> *const c_void { + unsafe { + let event_callback_context = &(*(event_callback_context_ptr as *mut EventCallbackContext)); + let _ = Box::from_raw(event_callback_context.ptr as *mut EventCallbackContextData); + } + std::ptr::null() +} + +impl EventTarget { + fn ptr(&self) -> *const OpaquePtr { + self.ptr + } + + pub fn context<'a>(&self) -> &'a ExecutingContext { + assert!(!self.context.is_null(), "Context PTR must not be null"); + unsafe { &*self.context } + } + + pub fn add_event_listener( + &self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState, + ) -> Result<(), String> { + let callback_context_data = Box::new(EventCallbackContextData { + executing_context_ptr: self.context().ptr, + executing_context_method_pointer: self.context().method_pointer(), + func: callback, + }); + let callback_context_data_ptr = Box::into_raw(callback_context_data); + let callback_context = Box::new(EventCallbackContext { callback: handle_event_listener_callback, free_ptr: handle_callback_data_free, ptr: callback_context_data_ptr }); + let callback_context_ptr = Box::into_raw(callback_context); + let c_event_name = CString::new(event_name).unwrap(); + unsafe { + ((*self.method_pointer).add_event_listener)(self.ptr, c_event_name.as_ptr(), callback_context_ptr, options, exception_state.ptr) + }; + if exception_state.has_exception() { + // Clean up the allocated memory on exception + unsafe { + let _ = Box::from_raw(callback_context_ptr); + let _ = Box::from_raw(callback_context_data_ptr); + } + return Err(exception_state.stringify(self.context())); + } + + Ok(()) + } + + pub fn remove_event_listener( + &self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState, + ) -> Result<(), String> { + let callback_context_data = Box::new(EventCallbackContextData { + executing_context_ptr: self.context().ptr, + executing_context_method_pointer: self.context().method_pointer(), + func: callback, + }); + let callback_context_data_ptr = Box::into_raw(callback_context_data); + let callback_context = Box::new(EventCallbackContext { callback: handle_event_listener_callback, free_ptr: handle_callback_data_free, ptr: callback_context_data_ptr }); + let callback_context_ptr = Box::into_raw(callback_context); + let c_event_name = CString::new(event_name).unwrap(); + unsafe { + ((*self.method_pointer).remove_event_listener)(self.ptr, c_event_name.as_ptr(), callback_context_ptr, exception_state.ptr) + }; + if exception_state.has_exception() { + unsafe { + let _ = Box::from_raw(callback_context_ptr); + let _ = Box::from_raw(callback_context_data_ptr); + } + return Err(exception_state.stringify(self.context())); + } + + Ok(()) + } + + pub fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dispatch_event)(self.ptr, event.ptr, exception_state.ptr) + } + } + + pub fn as_node(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::Node) + }; + if (raw_ptr.value == std::ptr::null()) { + return Err("The type value of event_target does not belong to the Node type."); + } + Ok(Node::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const NodeRustMethods, raw_ptr.status)) + } + + pub fn as_element(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::Element) + }; + if (raw_ptr.value == std::ptr::null()) { + return Err("The type value of event_target does not belong to the Element type."); + } + Ok(Element::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const ElementRustMethods, raw_ptr.status)) + } + + pub fn as_container_node(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::ContainerNode) + }; + if (raw_ptr.value == std::ptr::null()) { + return Err("The type value of event_target does not belong to the ContainerNode type."); + } + Ok(ContainerNode::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const ContainerNodeRustMethods, raw_ptr.status)) + } + + pub fn as_window(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::Window) + }; + if (raw_ptr.value == std::ptr::null()) { + return Err("The type value of event_target does not belong to the Window type."); + } + Ok(Window::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const WindowRustMethods, raw_ptr.status)) + } + + pub fn as_document(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::Document) + }; + if (raw_ptr.value == std::ptr::null()) { + return Err("The type value of event_target does not belong to the Document type."); + } + Ok(Document::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const DocumentRustMethods, raw_ptr.status)) + } + + pub fn as_html_element(&self) -> Result { + let raw_ptr = unsafe { + assert!(!(*((*self).status)).disposed, "The underline C++ impl of this ptr({:?}) had been disposed", (self.method_pointer)); + ((*self.method_pointer).dynamic_to)(self.ptr, EventTargetType::HTMLElement) + }; + if raw_ptr.value == std::ptr::null() { + return Err("The type value of event_target does not belong to the HTMLElement type."); + } + Ok(HTMLElement::initialize(raw_ptr.value, self.context, raw_ptr.method_pointer as *const HTMLElementRustMethods, raw_ptr.status)) + } +} + +pub trait EventTargetMethods { + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized; + + fn ptr(&self) -> *const OpaquePtr; + + // fn add_event_listener(&self, event_name: &str, callback: EventListenerCallback, options: &mut AddEventListenerOptions); + fn add_event_listener( + &self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String>; + + fn remove_event_listener( + &self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String>; + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool; +} + +impl Drop for EventTarget { + // When the holding on Rust side released, should notify c++ side to release the holder. + fn drop(&mut self) { + unsafe { + if (*((*self).status)).disposed { + println!("The object {:?} has been disposed.", self.ptr); + return; + }; + ((*self.method_pointer).release)(self.ptr) + }; + } +} + +impl EventTargetMethods for EventTarget { + /// Initialize the instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> EventTarget { + EventTarget { + ptr, + context, + method_pointer: method_pointer as *const EventTargetRustMethods, + status + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.ptr + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.dispatch_event(event, exception_state) + } +} diff --git a/bridge/rusty_webf_sys/src/exception_state.rs b/bridge/rusty_webf_sys/src/exception_state.rs new file mode 100644 index 0000000000..620a291745 --- /dev/null +++ b/bridge/rusty_webf_sys/src/exception_state.rs @@ -0,0 +1,72 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::{c_char, c_double, c_void}; +use std::{ptr}; +use libc::c_uint; +#[cfg(target_os = "windows")] +use windows::*; +use crate::executing_context::ExecutingContext; +use crate::memory_utils::safe_free_cpp_ptr; +use crate::OpaquePtr; + +#[repr(C)] +pub struct ExceptionStateRustMethods { + pub version: c_double, + pub has_exception: extern "C" fn(*const OpaquePtr) -> bool, + pub stringify: extern "C" fn( + executing_context: *const OpaquePtr, + shared_exception_state: *const OpaquePtr, + errmsg: *mut *mut c_char, + strlen: *mut c_uint, + ) -> c_void, +} + +pub struct ExceptionState { + pub ptr: *const OpaquePtr, + method_pointer: *const ExceptionStateRustMethods, +} + +impl ExceptionState { + /// Initialize the element instance from cpp raw pointer. + pub fn initialize(ptr: *const OpaquePtr, method_pointer: *const ExceptionStateRustMethods) -> ExceptionState { + ExceptionState { + ptr, + method_pointer, + } + } + + /// DOM operations may be failed due to other reasons. + /// Check the if this operation was success + pub fn has_exception(&self) -> bool { + return unsafe { + ((*self.method_pointer).has_exception)(self.ptr) + }; + } + + pub fn stringify(&self, context: &ExecutingContext) -> String { + let mut errmsg: *mut c_char = ptr::null_mut(); + let mut strlen: c_uint = 0; + + unsafe { + (((*self.method_pointer)).stringify)(context.ptr, self.ptr, &mut errmsg, &mut strlen); + + if errmsg.is_null() { + return String::new(); + } + let slice = std::slice::from_raw_parts(errmsg as *const u8, strlen as usize); + let message = String::from_utf8_lossy(slice).to_string(); + + // Free the allocated C string memory + safe_free_cpp_ptr(errmsg as *mut c_void); + return message; + } + } +} + +impl Drop for ExceptionState { + fn drop(&mut self) { + safe_free_cpp_ptr(self.ptr) + } +} \ No newline at end of file diff --git a/bridge/rusty_webf_sys/src/executing_context.rs b/bridge/rusty_webf_sys/src/executing_context.rs new file mode 100644 index 0000000000..44f9587cb3 --- /dev/null +++ b/bridge/rusty_webf_sys/src/executing_context.rs @@ -0,0 +1,82 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::{c_char, c_double, c_void}; +use std::ptr; +use libc; +use libc::c_uint; +use crate::document::{Document, DocumentRustMethods}; +use crate::event_target::EventTargetMethods; +use crate::exception_state::{ExceptionState, ExceptionStateRustMethods}; +use crate::{OpaquePtr, RustValue}; +use crate::custom_event::{CustomEvent, CustomEventRustMethods}; +use crate::window::{Window, WindowRustMethods}; + +#[repr(C)] +pub struct ExecutingContextRustMethods { + pub version: c_double, + pub get_document: extern "C" fn(*const OpaquePtr) -> RustValue, + pub get_window: extern "C" fn(*const OpaquePtr) -> RustValue, + pub create_exception_state: extern "C" fn() -> RustValue, + pub create_custom_event: extern "C" fn() -> RustValue, +} + +/// An environment contains all the necessary running states of a web page. +/// +/// For Flutter apps, there could be many web pages running in the same Dart environment, +/// and each web page is isolated with its own DOM tree, layout state, and JavaScript running environment. +/// +/// In the Rust world, Rust code plays the same role as JavaScript, +/// so the Rust running states also live in the ExecutionContext class. +/// +/// Since both JavaScript and Rust run in the same environment, +/// the DOM tree and the underlying layout state are shared between Rust and JavaScript worlds. +/// it's possible to create an HTMLElement in Rust and remove it from JavaScript, +/// and even collaborate with each other to build an enormous application. +/// +/// The relationship between Window, Document, and ExecutionContext is 1:1:1 at any point in time. +pub struct ExecutingContext { + // The underlying pointer points to the actual implementation of ExecutionContext in the C++ world. + pub ptr: *const OpaquePtr, + // Methods available for export from the C++ world for use. + method_pointer: *const ExecutingContextRustMethods, +} + +impl ExecutingContext { + pub fn initialize(ptr: *const OpaquePtr, method_pointer: *const ExecutingContextRustMethods) -> ExecutingContext { + ExecutingContext { + ptr, + method_pointer + } + } + + pub fn method_pointer<'a>(&self) -> &'a ExecutingContextRustMethods { + unsafe { + &*self.method_pointer + } + } + + /// Obtain the window instance from ExecutingContext. + pub fn window(&self) -> Window { + let result = unsafe { + ((*self.method_pointer).get_window)(self.ptr) + }; + return Window::initialize(result.value, self, result.method_pointer, result.status); + } + + /// Obtain the document instance from ExecutingContext. + pub fn document(&self) -> Document { + let result = unsafe { + ((*self.method_pointer).get_document)(self.ptr) + }; + return Document::initialize::(result.value, self, result.method_pointer, result.status); + } + + pub fn create_exception_state(&self) -> ExceptionState { + let result = unsafe { + ((*self.method_pointer).create_exception_state)() + }; + ExceptionState::initialize(result.value, result.method_pointer) + } +} diff --git a/bridge/rusty_webf_sys/src/focus_event.rs b/bridge/rusty_webf_sys/src/focus_event.rs new file mode 100644 index 0000000000..a7118a5c5f --- /dev/null +++ b/bridge/rusty_webf_sys/src/focus_event.rs @@ -0,0 +1,120 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct FocusEventRustMethods { + pub version: c_double, + pub ui_event: *const UIEventRustMethods, + pub related_target: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, +} +pub struct FocusEvent { + pub ui_event: UIEvent, + method_pointer: *const FocusEventRustMethods, +} +impl FocusEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const FocusEventRustMethods, status: *const RustValueStatus) -> FocusEvent { + unsafe { + FocusEvent { + ui_event: UIEvent::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().ui_event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.ui_event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.ui_event.context() + } + pub fn related_target(&self) -> EventTarget { + let value = unsafe { + ((*self.method_pointer).related_target)(self.ptr()) + }; + EventTarget::initialize(value.value, self.context(), value.method_pointer, value.status) + } +} +pub trait FocusEventMethods: UIEventMethods { + fn related_target(&self) -> EventTarget; + fn as_focus_event(&self) -> &FocusEvent; +} +impl FocusEventMethods for FocusEvent { + fn related_target(&self) -> EventTarget { + self.related_target() + } + fn as_focus_event(&self) -> &FocusEvent { + self + } +} +impl UIEventMethods for FocusEvent { + fn detail(&self) -> f64 { + self.ui_event.detail() + } + fn view(&self) -> Window { + self.ui_event.view() + } + fn which(&self) -> f64 { + self.ui_event.which() + } + fn as_ui_event(&self) -> &UIEvent { + &self.ui_event + } +} +impl EventMethods for FocusEvent { + fn bubbles(&self) -> bool { + self.ui_event.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.ui_event.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.ui_event.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.ui_event.event.current_target() + } + fn default_prevented(&self) -> bool { + self.ui_event.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.ui_event.event.src_element() + } + fn target(&self) -> EventTarget { + self.ui_event.event.target() + } + fn is_trusted(&self) -> bool { + self.ui_event.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.ui_event.event.time_stamp() + } + fn type_(&self) -> String { + self.ui_event.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.ui_event.event + } +} diff --git a/bridge/rusty_webf_sys/src/focus_event_init.rs b/bridge/rusty_webf_sys/src/focus_event_init.rs new file mode 100644 index 0000000000..7210d9029d --- /dev/null +++ b/bridge/rusty_webf_sys/src/focus_event_init.rs @@ -0,0 +1,14 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct FocusEventInit { + pub detail: c_double, + pub view: RustValue, + pub which: c_double, + pub related_target: RustValue, +} diff --git a/bridge/rusty_webf_sys/src/gesture_event.rs b/bridge/rusty_webf_sys/src/gesture_event.rs new file mode 100644 index 0000000000..80efcda849 --- /dev/null +++ b/bridge/rusty_webf_sys/src/gesture_event.rs @@ -0,0 +1,185 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct GestureEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub state: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub direction: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub delta_x: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub delta_y: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub velocity_x: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub velocity_y: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub scale: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub rotation: extern "C" fn(ptr: *const OpaquePtr) -> c_double, +} +pub struct GestureEvent { + pub event: Event, + method_pointer: *const GestureEventRustMethods, +} +impl GestureEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const GestureEventRustMethods, status: *const RustValueStatus) -> GestureEvent { + unsafe { + GestureEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn state(&self) -> String { + let value = unsafe { + ((*self.method_pointer).state)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn direction(&self) -> String { + let value = unsafe { + ((*self.method_pointer).direction)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn delta_x(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).delta_x)(self.ptr()) + }; + value + } + pub fn delta_y(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).delta_y)(self.ptr()) + }; + value + } + pub fn velocity_x(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).velocity_x)(self.ptr()) + }; + value + } + pub fn velocity_y(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).velocity_y)(self.ptr()) + }; + value + } + pub fn scale(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).scale)(self.ptr()) + }; + value + } + pub fn rotation(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).rotation)(self.ptr()) + }; + value + } +} +pub trait GestureEventMethods: EventMethods { + fn state(&self) -> String; + fn direction(&self) -> String; + fn delta_x(&self) -> f64; + fn delta_y(&self) -> f64; + fn velocity_x(&self) -> f64; + fn velocity_y(&self) -> f64; + fn scale(&self) -> f64; + fn rotation(&self) -> f64; + fn as_gesture_event(&self) -> &GestureEvent; +} +impl GestureEventMethods for GestureEvent { + fn state(&self) -> String { + self.state() + } + fn direction(&self) -> String { + self.direction() + } + fn delta_x(&self) -> f64 { + self.delta_x() + } + fn delta_y(&self) -> f64 { + self.delta_y() + } + fn velocity_x(&self) -> f64 { + self.velocity_x() + } + fn velocity_y(&self) -> f64 { + self.velocity_y() + } + fn scale(&self) -> f64 { + self.scale() + } + fn rotation(&self) -> f64 { + self.rotation() + } + fn as_gesture_event(&self) -> &GestureEvent { + self + } +} +impl EventMethods for GestureEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/gesture_event_init.rs b/bridge/rusty_webf_sys/src/gesture_event_init.rs new file mode 100644 index 0000000000..29d5519ae1 --- /dev/null +++ b/bridge/rusty_webf_sys/src/gesture_event_init.rs @@ -0,0 +1,21 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct GestureEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub state: *const c_char, + pub direction: *const c_char, + pub delta_x: c_double, + pub delta_y: c_double, + pub velocity_x: c_double, + pub velocity_y: c_double, + pub scale: c_double, + pub rotation: c_double, +} diff --git a/bridge/rusty_webf_sys/src/hashchange_event.rs b/bridge/rusty_webf_sys/src/hashchange_event.rs new file mode 100644 index 0000000000..7da9251de5 --- /dev/null +++ b/bridge/rusty_webf_sys/src/hashchange_event.rs @@ -0,0 +1,119 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct HashchangeEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub new_url: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub old_url: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, +} +pub struct HashchangeEvent { + pub event: Event, + method_pointer: *const HashchangeEventRustMethods, +} +impl HashchangeEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const HashchangeEventRustMethods, status: *const RustValueStatus) -> HashchangeEvent { + unsafe { + HashchangeEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn new_url(&self) -> String { + let value = unsafe { + ((*self.method_pointer).new_url)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn old_url(&self) -> String { + let value = unsafe { + ((*self.method_pointer).old_url)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } +} +pub trait HashchangeEventMethods: EventMethods { + fn new_url(&self) -> String; + fn old_url(&self) -> String; + fn as_hashchange_event(&self) -> &HashchangeEvent; +} +impl HashchangeEventMethods for HashchangeEvent { + fn new_url(&self) -> String { + self.new_url() + } + fn old_url(&self) -> String { + self.old_url() + } + fn as_hashchange_event(&self) -> &HashchangeEvent { + self + } +} +impl EventMethods for HashchangeEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/hashchange_event_init.rs b/bridge/rusty_webf_sys/src/hashchange_event_init.rs new file mode 100644 index 0000000000..79de869114 --- /dev/null +++ b/bridge/rusty_webf_sys/src/hashchange_event_init.rs @@ -0,0 +1,15 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct HashchangeEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub old_url: *const c_char, + pub new_url: *const c_char, +} diff --git a/bridge/rusty_webf_sys/src/html_element.rs b/bridge/rusty_webf_sys/src/html_element.rs new file mode 100644 index 0000000000..d8cec4ba53 --- /dev/null +++ b/bridge/rusty_webf_sys/src/html_element.rs @@ -0,0 +1,82 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct HTMLElementRustMethods { + pub version: c_double, + pub element: ElementRustMethods, +} + +impl RustMethods for HTMLElementRustMethods {} + +pub struct HTMLElement { + element: Element, + method_pointer: *const HTMLElementRustMethods, +} + +pub trait HTMLElementMethods: ElementMethods {} + +impl ElementMethods for HTMLElement {} + +impl ContainerNodeMethods for HTMLElement {} + +impl NodeMethods for HTMLElement { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.element.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.element.remove_child(target_node, exception_state) + } + + fn as_node(&self) -> &Node { + self.element.as_node() + } +} + +impl EventTargetMethods for HTMLElement { + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + HTMLElement { + element: Element::initialize( + ptr, + context, + &(method_pointer as *const HTMLElementRustMethods).as_ref().unwrap().element, + status + ), + method_pointer: method_pointer as *const HTMLElementRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.element.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.element.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.element.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.element.dispatch_event(event, exception_state) + } +} + +impl HTMLElementMethods for HTMLElement { + +} diff --git a/bridge/rusty_webf_sys/src/input_event.rs b/bridge/rusty_webf_sys/src/input_event.rs new file mode 100644 index 0000000000..9485750fbf --- /dev/null +++ b/bridge/rusty_webf_sys/src/input_event.rs @@ -0,0 +1,133 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct InputEventRustMethods { + pub version: c_double, + pub ui_event: *const UIEventRustMethods, + pub input_type: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub data: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, +} +pub struct InputEvent { + pub ui_event: UIEvent, + method_pointer: *const InputEventRustMethods, +} +impl InputEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const InputEventRustMethods, status: *const RustValueStatus) -> InputEvent { + unsafe { + InputEvent { + ui_event: UIEvent::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().ui_event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.ui_event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.ui_event.context() + } + pub fn input_type(&self) -> String { + let value = unsafe { + ((*self.method_pointer).input_type)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn data(&self) -> String { + let value = unsafe { + ((*self.method_pointer).data)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } +} +pub trait InputEventMethods: UIEventMethods { + fn input_type(&self) -> String; + fn data(&self) -> String; + fn as_input_event(&self) -> &InputEvent; +} +impl InputEventMethods for InputEvent { + fn input_type(&self) -> String { + self.input_type() + } + fn data(&self) -> String { + self.data() + } + fn as_input_event(&self) -> &InputEvent { + self + } +} +impl UIEventMethods for InputEvent { + fn detail(&self) -> f64 { + self.ui_event.detail() + } + fn view(&self) -> Window { + self.ui_event.view() + } + fn which(&self) -> f64 { + self.ui_event.which() + } + fn as_ui_event(&self) -> &UIEvent { + &self.ui_event + } +} +impl EventMethods for InputEvent { + fn bubbles(&self) -> bool { + self.ui_event.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.ui_event.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.ui_event.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.ui_event.event.current_target() + } + fn default_prevented(&self) -> bool { + self.ui_event.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.ui_event.event.src_element() + } + fn target(&self) -> EventTarget { + self.ui_event.event.target() + } + fn is_trusted(&self) -> bool { + self.ui_event.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.ui_event.event.time_stamp() + } + fn type_(&self) -> String { + self.ui_event.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.ui_event.event + } +} diff --git a/bridge/rusty_webf_sys/src/input_event_init.rs b/bridge/rusty_webf_sys/src/input_event_init.rs new file mode 100644 index 0000000000..9c85bc478a --- /dev/null +++ b/bridge/rusty_webf_sys/src/input_event_init.rs @@ -0,0 +1,15 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct InputEventInit { + pub detail: c_double, + pub view: RustValue, + pub which: c_double, + pub input_type: *const c_char, + pub data: *const c_char, +} diff --git a/bridge/rusty_webf_sys/src/intersection_change_event.rs b/bridge/rusty_webf_sys/src/intersection_change_event.rs new file mode 100644 index 0000000000..cce4cc49a7 --- /dev/null +++ b/bridge/rusty_webf_sys/src/intersection_change_event.rs @@ -0,0 +1,106 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct IntersectionChangeEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub intersection_ratio: extern "C" fn(ptr: *const OpaquePtr) -> c_double, +} +pub struct IntersectionChangeEvent { + pub event: Event, + method_pointer: *const IntersectionChangeEventRustMethods, +} +impl IntersectionChangeEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const IntersectionChangeEventRustMethods, status: *const RustValueStatus) -> IntersectionChangeEvent { + unsafe { + IntersectionChangeEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn intersection_ratio(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).intersection_ratio)(self.ptr()) + }; + value + } +} +pub trait IntersectionChangeEventMethods: EventMethods { + fn intersection_ratio(&self) -> f64; + fn as_intersection_change_event(&self) -> &IntersectionChangeEvent; +} +impl IntersectionChangeEventMethods for IntersectionChangeEvent { + fn intersection_ratio(&self) -> f64 { + self.intersection_ratio() + } + fn as_intersection_change_event(&self) -> &IntersectionChangeEvent { + self + } +} +impl EventMethods for IntersectionChangeEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/intersection_change_event_init.rs b/bridge/rusty_webf_sys/src/intersection_change_event_init.rs new file mode 100644 index 0000000000..f426f2e45e --- /dev/null +++ b/bridge/rusty_webf_sys/src/intersection_change_event_init.rs @@ -0,0 +1,14 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct IntersectionChangeEventInit { + pub detail: c_double, + pub view: RustValue, + pub which: c_double, + pub intersection_ratio: c_double, +} diff --git a/bridge/rusty_webf_sys/src/keyboard_event_init.rs b/bridge/rusty_webf_sys/src/keyboard_event_init.rs new file mode 100644 index 0000000000..2f793ce90a --- /dev/null +++ b/bridge/rusty_webf_sys/src/keyboard_event_init.rs @@ -0,0 +1,24 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct KeyboardEventInit { + pub detail: c_double, + pub view: RustValue, + pub which: c_double, + pub alt_key: i32, + pub char_code: c_double, + pub code: *const c_char, + pub ctrl_key: i32, + pub is_composing: i32, + pub key: *const c_char, + pub key_code: c_double, + pub location: c_double, + pub meta_key: i32, + pub repeat: i32, + pub shift_key: i32, +} diff --git a/bridge/rusty_webf_sys/src/lib.rs b/bridge/rusty_webf_sys/src/lib.rs new file mode 100644 index 0000000000..99e891033a --- /dev/null +++ b/bridge/rusty_webf_sys/src/lib.rs @@ -0,0 +1,122 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use crate::executing_context::{ExecutingContext, ExecutingContextRustMethods}; + +pub mod executing_context; +pub mod document; +pub mod window; +pub mod element; +pub mod document_fragment; +pub mod node; +pub mod event_target; +pub mod event; +pub mod animation_event; +pub mod close_event; +pub mod focus_event; +pub mod gesture_event; +pub mod hashchange_event; +pub mod input_event; +pub mod intersection_change_event; +pub mod mouse_event; +pub mod pointer_event; +pub mod transition_event; +pub mod ui_event; +pub mod container_node; +pub mod exception_state; +pub mod text; +pub mod comment; +pub mod character_data; +pub mod html_element; +pub mod script_value_ref; +pub mod custom_event; +pub mod add_event_listener_options; +pub mod animation_event_init; +pub mod close_event_init; +pub mod event_init; +pub mod event_listener_options; +pub mod focus_event_init; +pub mod gesture_event_init; +pub mod hashchange_event_init; +pub mod input_event_init; +pub mod intersection_change_event_init; +pub mod keyboard_event_init; +pub mod mouse_event_init; +pub mod pointer_event_init; +pub mod scroll_options; +pub mod scroll_to_options; +pub mod touch_init; +pub mod transition_event_init; +pub mod ui_event_init; +mod memory_utils; + +pub use executing_context::*; +pub use document::*; +pub use window::*; +pub use element::*; +pub use document_fragment::*; +pub use node::*; +pub use event_target::*; +pub use event::*; +pub use animation_event::*; +pub use close_event::*; +pub use focus_event::*; +pub use gesture_event::*; +pub use hashchange_event::*; +pub use input_event::*; +pub use intersection_change_event::*; +pub use mouse_event::*; +pub use pointer_event::*; +pub use transition_event::*; +pub use ui_event::*; +pub use container_node::*; +pub use exception_state::*; +pub use text::*; +pub use comment::*; +pub use character_data::*; +pub use html_element::*; +pub use script_value_ref::*; +pub use add_event_listener_options::*; +pub use animation_event_init::*; +pub use close_event_init::*; +pub use event_init::*; +pub use event_listener_options::*; +pub use focus_event_init::*; +pub use gesture_event_init::*; +pub use hashchange_event_init::*; +pub use input_event_init::*; +pub use intersection_change_event_init::*; +pub use keyboard_event_init::*; +pub use mouse_event_init::*; +pub use pointer_event_init::*; +pub use scroll_options::*; +pub use scroll_to_options::*; +pub use touch_init::*; +pub use transition_event_init::*; +pub use ui_event_init::*; + +#[repr(C)] +pub struct OpaquePtr; + +#[repr(C)] +pub struct RustValueStatus { + pub disposed: bool, +} + +#[repr(C)] +pub struct RustValue { + pub value: *const OpaquePtr, + pub method_pointer: *const T, + pub status: *const RustValueStatus, +} + +pub fn initialize_webf_api(value: RustValue) -> ExecutingContext { + ExecutingContext::initialize(value.value, value.method_pointer) +} + +// This is the entrypoint when your rust app compiled as dynamic library and loaded & executed by WebF. +// #[no_mangle] +// pub extern "C" fn load_webf_rust_module(context: *mut c_void, method_pointer: *const c_void) { +// +// } diff --git a/bridge/rusty_webf_sys/src/memory_utils.rs b/bridge/rusty_webf_sys/src/memory_utils.rs new file mode 100644 index 0000000000..22a447eb2d --- /dev/null +++ b/bridge/rusty_webf_sys/src/memory_utils.rs @@ -0,0 +1,21 @@ +#[cfg(target_os = "windows")] +use windows::Win32; +use libc; +use crate::OpaquePtr; + +pub fn safe_free_cpp_ptr(ptr: *const T) { + unsafe { + if cfg!(target_os = "windows") { + #[cfg(target_os = "windows")] + { + Win32::System::Memory::HeapFree( + Win32::System::Memory::GetProcessHeap().unwrap(), + Win32::System::Memory::HEAP_FLAGS(0), + Option::from(ptr as *const libc::c_void) + ).expect("Failed to call HeapFree"); + } + } else { + libc::free(ptr.cast_mut() as *mut libc::c_void); + } + } +} \ No newline at end of file diff --git a/bridge/rusty_webf_sys/src/mouse_event.rs b/bridge/rusty_webf_sys/src/mouse_event.rs new file mode 100644 index 0000000000..776d4d7c3a --- /dev/null +++ b/bridge/rusty_webf_sys/src/mouse_event.rs @@ -0,0 +1,153 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct MouseEventRustMethods { + pub version: c_double, + pub ui_event: *const UIEventRustMethods, + pub client_x: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub client_y: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub offset_x: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub offset_y: extern "C" fn(ptr: *const OpaquePtr) -> c_double, +} +pub struct MouseEvent { + pub ui_event: UIEvent, + method_pointer: *const MouseEventRustMethods, +} +impl MouseEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const MouseEventRustMethods, status: *const RustValueStatus) -> MouseEvent { + unsafe { + MouseEvent { + ui_event: UIEvent::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().ui_event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.ui_event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.ui_event.context() + } + pub fn client_x(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).client_x)(self.ptr()) + }; + value + } + pub fn client_y(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).client_y)(self.ptr()) + }; + value + } + pub fn offset_x(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).offset_x)(self.ptr()) + }; + value + } + pub fn offset_y(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).offset_y)(self.ptr()) + }; + value + } +} +pub trait MouseEventMethods: UIEventMethods { + fn client_x(&self) -> f64; + fn client_y(&self) -> f64; + fn offset_x(&self) -> f64; + fn offset_y(&self) -> f64; + fn as_mouse_event(&self) -> &MouseEvent; +} +impl MouseEventMethods for MouseEvent { + fn client_x(&self) -> f64 { + self.client_x() + } + fn client_y(&self) -> f64 { + self.client_y() + } + fn offset_x(&self) -> f64 { + self.offset_x() + } + fn offset_y(&self) -> f64 { + self.offset_y() + } + fn as_mouse_event(&self) -> &MouseEvent { + self + } +} +impl UIEventMethods for MouseEvent { + fn detail(&self) -> f64 { + self.ui_event.detail() + } + fn view(&self) -> Window { + self.ui_event.view() + } + fn which(&self) -> f64 { + self.ui_event.which() + } + fn as_ui_event(&self) -> &UIEvent { + &self.ui_event + } +} +impl EventMethods for MouseEvent { + fn bubbles(&self) -> bool { + self.ui_event.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.ui_event.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.ui_event.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.ui_event.event.current_target() + } + fn default_prevented(&self) -> bool { + self.ui_event.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.ui_event.event.src_element() + } + fn target(&self) -> EventTarget { + self.ui_event.event.target() + } + fn is_trusted(&self) -> bool { + self.ui_event.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.ui_event.event.time_stamp() + } + fn type_(&self) -> String { + self.ui_event.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.ui_event.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.ui_event.event + } +} diff --git a/bridge/rusty_webf_sys/src/mouse_event_init.rs b/bridge/rusty_webf_sys/src/mouse_event_init.rs new file mode 100644 index 0000000000..d2619818a4 --- /dev/null +++ b/bridge/rusty_webf_sys/src/mouse_event_init.rs @@ -0,0 +1,13 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct MouseEventInit { + pub detail: c_double, + pub view: RustValue, + pub which: c_double, +} diff --git a/bridge/rusty_webf_sys/src/node.rs b/bridge/rusty_webf_sys/src/node.rs new file mode 100644 index 0000000000..25d0905183 --- /dev/null +++ b/bridge/rusty_webf_sys/src/node.rs @@ -0,0 +1,137 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +enum NodeType { + ElementNode, + AttributeNode, + TextNode, + CommentNode, + DocumentNode, + DocumentTypeNode, + DocumentFragmentNode, +} + +impl NodeType { + fn value(&self) -> i32 { + match self { + NodeType::ElementNode => 1, + NodeType::AttributeNode => 2, + NodeType::TextNode => 3, + NodeType::CommentNode => 8, + NodeType::DocumentNode => 9, + NodeType::DocumentTypeNode => 10, + NodeType::DocumentFragmentNode => 11, + } + } +} + +#[repr(C)] +pub struct NodeRustMethods { + pub version: c_double, + pub event_target: EventTargetRustMethods, + pub append_child: extern "C" fn(self_node: *const OpaquePtr, new_node: *const OpaquePtr, exception_state: *const OpaquePtr) -> RustValue, + pub remove_node: extern "C" fn(self_node: *const OpaquePtr, target_node: *const OpaquePtr, exception_state: *const OpaquePtr) -> RustValue, +} + +impl RustMethods for NodeRustMethods {} + +pub struct Node { + pub event_target: EventTarget, + method_pointer: *const NodeRustMethods, +} + +impl Node { + /// The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. + pub fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.event_target; + let returned_result = unsafe { + ((*self.method_pointer).append_child)(event_target.ptr, new_node.ptr(), exception_state.ptr) + }; + if (exception_state.has_exception()) { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Node::initialize(returned_result.value, event_target.context(), returned_result.method_pointer, returned_result.status)); + } + + /// The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node. + pub fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + let event_target: &EventTarget = &self.event_target; + let returned_result = unsafe { + ((*self.method_pointer).remove_node)(event_target.ptr, target_node.ptr(), exception_state.ptr) + }; + if (exception_state.has_exception()) { + return Err(exception_state.stringify(event_target.context())); + } + + return Ok(Node::initialize(returned_result.value, event_target.context(), returned_result.method_pointer, returned_result.status)); + } +} + +pub trait NodeMethods: EventTargetMethods { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result; + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result; + + fn as_node(&self) -> &Node; +} + +impl EventTargetMethods for Node { + /// Initialize the instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + Node { + event_target: EventTarget::initialize( + ptr, + context, + &(method_pointer as *const NodeRustMethods).as_ref().unwrap().event_target, + status, + ), + method_pointer: method_pointer as *const NodeRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.event_target.ptr + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.event_target.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.event_target.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, + event: &Event, + exception_state: &ExceptionState) -> bool{ + self.event_target.dispatch_event(event, exception_state) + } +} + +impl NodeMethods for Node { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.remove_child(target_node, exception_state) + } + + fn as_node(&self) -> &Node { + self + } +} diff --git a/bridge/rusty_webf_sys/src/pointer_event.rs b/bridge/rusty_webf_sys/src/pointer_event.rs new file mode 100644 index 0000000000..04493a9425 --- /dev/null +++ b/bridge/rusty_webf_sys/src/pointer_event.rs @@ -0,0 +1,237 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct PointerEventRustMethods { + pub version: c_double, + pub mouse_event: *const MouseEventRustMethods, + pub height: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub is_primary: extern "C" fn(ptr: *const OpaquePtr) -> i32, + pub pointer_id: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub pointer_type: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub pressure: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub tangential_pressure: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub tilt_x: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub tilt_y: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub twist: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub width: extern "C" fn(ptr: *const OpaquePtr) -> c_double, +} +pub struct PointerEvent { + pub mouse_event: MouseEvent, + method_pointer: *const PointerEventRustMethods, +} +impl PointerEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const PointerEventRustMethods, status: *const RustValueStatus) -> PointerEvent { + unsafe { + PointerEvent { + mouse_event: MouseEvent::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().mouse_event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.mouse_event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.mouse_event.context() + } + pub fn height(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).height)(self.ptr()) + }; + value + } + pub fn is_primary(&self) -> bool { + let value = unsafe { + ((*self.method_pointer).is_primary)(self.ptr()) + }; + value != 0 + } + pub fn pointer_id(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).pointer_id)(self.ptr()) + }; + value + } + pub fn pointer_type(&self) -> String { + let value = unsafe { + ((*self.method_pointer).pointer_type)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn pressure(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).pressure)(self.ptr()) + }; + value + } + pub fn tangential_pressure(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).tangential_pressure)(self.ptr()) + }; + value + } + pub fn tilt_x(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).tilt_x)(self.ptr()) + }; + value + } + pub fn tilt_y(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).tilt_y)(self.ptr()) + }; + value + } + pub fn twist(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).twist)(self.ptr()) + }; + value + } + pub fn width(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).width)(self.ptr()) + }; + value + } +} +pub trait PointerEventMethods: MouseEventMethods { + fn height(&self) -> f64; + fn is_primary(&self) -> bool; + fn pointer_id(&self) -> f64; + fn pointer_type(&self) -> String; + fn pressure(&self) -> f64; + fn tangential_pressure(&self) -> f64; + fn tilt_x(&self) -> f64; + fn tilt_y(&self) -> f64; + fn twist(&self) -> f64; + fn width(&self) -> f64; + fn as_pointer_event(&self) -> &PointerEvent; +} +impl PointerEventMethods for PointerEvent { + fn height(&self) -> f64 { + self.height() + } + fn is_primary(&self) -> bool { + self.is_primary() + } + fn pointer_id(&self) -> f64 { + self.pointer_id() + } + fn pointer_type(&self) -> String { + self.pointer_type() + } + fn pressure(&self) -> f64 { + self.pressure() + } + fn tangential_pressure(&self) -> f64 { + self.tangential_pressure() + } + fn tilt_x(&self) -> f64 { + self.tilt_x() + } + fn tilt_y(&self) -> f64 { + self.tilt_y() + } + fn twist(&self) -> f64 { + self.twist() + } + fn width(&self) -> f64 { + self.width() + } + fn as_pointer_event(&self) -> &PointerEvent { + self + } +} +impl MouseEventMethods for PointerEvent { + fn client_x(&self) -> f64 { + self.mouse_event.client_x() + } + fn client_y(&self) -> f64 { + self.mouse_event.client_y() + } + fn offset_x(&self) -> f64 { + self.mouse_event.offset_x() + } + fn offset_y(&self) -> f64 { + self.mouse_event.offset_y() + } + fn as_mouse_event(&self) -> &MouseEvent { + &self.mouse_event + } +} +impl UIEventMethods for PointerEvent { + fn detail(&self) -> f64 { + self.mouse_event.ui_event.detail() + } + fn view(&self) -> Window { + self.mouse_event.ui_event.view() + } + fn which(&self) -> f64 { + self.mouse_event.ui_event.which() + } + fn as_ui_event(&self) -> &UIEvent { + &self.mouse_event.ui_event + } +} +impl EventMethods for PointerEvent { + fn bubbles(&self) -> bool { + self.mouse_event.ui_event.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.mouse_event.ui_event.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.mouse_event.ui_event.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.mouse_event.ui_event.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.mouse_event.ui_event.event.current_target() + } + fn default_prevented(&self) -> bool { + self.mouse_event.ui_event.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.mouse_event.ui_event.event.src_element() + } + fn target(&self) -> EventTarget { + self.mouse_event.ui_event.event.target() + } + fn is_trusted(&self) -> bool { + self.mouse_event.ui_event.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.mouse_event.ui_event.event.time_stamp() + } + fn type_(&self) -> String { + self.mouse_event.ui_event.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.mouse_event.ui_event.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.mouse_event.ui_event.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.mouse_event.ui_event.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.mouse_event.ui_event.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.mouse_event.ui_event.event + } +} diff --git a/bridge/rusty_webf_sys/src/pointer_event_init.rs b/bridge/rusty_webf_sys/src/pointer_event_init.rs new file mode 100644 index 0000000000..d76286ad77 --- /dev/null +++ b/bridge/rusty_webf_sys/src/pointer_event_init.rs @@ -0,0 +1,20 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct PointerEventInit { + pub is_primary: i32, + pub pointer_id: c_double, + pub pointer_type: *const c_char, + pub pressure: c_double, + pub tangential_pressure: c_double, + pub tilt_x: c_double, + pub tilt_y: c_double, + pub twist: c_double, + pub width: c_double, + pub height: c_double, +} diff --git a/bridge/rusty_webf_sys/src/script_value_ref.rs b/bridge/rusty_webf_sys/src/script_value_ref.rs new file mode 100644 index 0000000000..28aa196177 --- /dev/null +++ b/bridge/rusty_webf_sys/src/script_value_ref.rs @@ -0,0 +1,24 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::{c_double, c_void}; +use crate::*; + +#[repr(C)] +pub struct ScriptValueRefRustMethods { + pub release: extern "C" fn(script_value_ref: *const OpaquePtr) -> c_void, +} + +pub struct ScriptValueRef { + pub ptr: *const OpaquePtr, + pub method_pointer: *const ScriptValueRefRustMethods, +} + +impl Drop for ScriptValueRef { + fn drop(&mut self) { + unsafe { + ((*self.method_pointer).release)(self.ptr) + }; + } +} \ No newline at end of file diff --git a/bridge/rusty_webf_sys/src/scroll_options.rs b/bridge/rusty_webf_sys/src/scroll_options.rs new file mode 100644 index 0000000000..a28d104213 --- /dev/null +++ b/bridge/rusty_webf_sys/src/scroll_options.rs @@ -0,0 +1,11 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct ScrollOptions { + pub behavior: *const c_char, +} diff --git a/bridge/rusty_webf_sys/src/scroll_to_options.rs b/bridge/rusty_webf_sys/src/scroll_to_options.rs new file mode 100644 index 0000000000..9fee3ebd57 --- /dev/null +++ b/bridge/rusty_webf_sys/src/scroll_to_options.rs @@ -0,0 +1,13 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct ScrollToOptions { + pub behavior: *const c_char, + pub top: c_double, + pub left: c_double, +} diff --git a/bridge/rusty_webf_sys/src/text.rs b/bridge/rusty_webf_sys/src/text.rs new file mode 100644 index 0000000000..13ba299868 --- /dev/null +++ b/bridge/rusty_webf_sys/src/text.rs @@ -0,0 +1,72 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::*; +use crate::*; + +#[repr(C)] +pub struct TextNodeRustMethods { + pub version: c_double, + pub character_data: CharacterDataRustMethods, +} + +impl RustMethods for TextNodeRustMethods {} + +pub struct Text { + pub character_data: CharacterData, + method_pointer: *const TextNodeRustMethods, +} + +impl Text { +} + +impl NodeMethods for Text { + fn append_child(&self, new_node: &Node, exception_state: &ExceptionState) -> Result { + self.character_data.node.append_child(new_node, exception_state) + } + + fn remove_child(&self, target_node: &Node, exception_state: &ExceptionState) -> Result { + self.character_data.node.remove_child(target_node, exception_state) + } + + + fn as_node(&self) -> &Node { + &self.character_data.node + } +} + +impl EventTargetMethods for Text { + /// Initialize the instance from cpp raw pointer. + fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const T, status: *const RustValueStatus) -> Self where Self: Sized { + unsafe { + Text { + character_data: CharacterData::initialize(ptr, context, &(method_pointer as *const TextNodeRustMethods).as_ref().unwrap().character_data, status), + method_pointer: method_pointer as *const TextNodeRustMethods, + } + } + } + + fn ptr(&self) -> *const OpaquePtr { + self.character_data.ptr() + } + + fn add_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + options: &AddEventListenerOptions, + exception_state: &ExceptionState) -> Result<(), String> { + self.character_data.add_event_listener(event_name, callback, options, exception_state) + } + + fn remove_event_listener(&self, + event_name: &str, + callback: EventListenerCallback, + exception_state: &ExceptionState) -> Result<(), String> { + self.character_data.remove_event_listener(event_name, callback, exception_state) + } + + fn dispatch_event(&self, event: &Event, exception_state: &ExceptionState) -> bool { + self.character_data.dispatch_event(event, exception_state) + } +} diff --git a/bridge/rusty_webf_sys/src/touch_init.rs b/bridge/rusty_webf_sys/src/touch_init.rs new file mode 100644 index 0000000000..de06dd9b8f --- /dev/null +++ b/bridge/rusty_webf_sys/src/touch_init.rs @@ -0,0 +1,22 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct TouchInit { + pub identifier: c_double, + pub target: RustValue, + pub client_x: c_double, + pub client_y: c_double, + pub screen_x: c_double, + pub screen_y: c_double, + pub page_x: c_double, + pub page_y: c_double, + pub radius_x: c_double, + pub radius_y: c_double, + pub rotation_angle: c_double, + pub force: c_double, +} diff --git a/bridge/rusty_webf_sys/src/transition_event.rs b/bridge/rusty_webf_sys/src/transition_event.rs new file mode 100644 index 0000000000..3a228a54aa --- /dev/null +++ b/bridge/rusty_webf_sys/src/transition_event.rs @@ -0,0 +1,130 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct TransitionEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub elapsed_time: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub property_name: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, + pub pseudo_element: extern "C" fn(ptr: *const OpaquePtr) -> *const c_char, +} +pub struct TransitionEvent { + pub event: Event, + method_pointer: *const TransitionEventRustMethods, +} +impl TransitionEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const TransitionEventRustMethods, status: *const RustValueStatus) -> TransitionEvent { + unsafe { + TransitionEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn elapsed_time(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).elapsed_time)(self.ptr()) + }; + value + } + pub fn property_name(&self) -> String { + let value = unsafe { + ((*self.method_pointer).property_name)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } + pub fn pseudo_element(&self) -> String { + let value = unsafe { + ((*self.method_pointer).pseudo_element)(self.ptr()) + }; + let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string() + } +} +pub trait TransitionEventMethods: EventMethods { + fn elapsed_time(&self) -> f64; + fn property_name(&self) -> String; + fn pseudo_element(&self) -> String; + fn as_transition_event(&self) -> &TransitionEvent; +} +impl TransitionEventMethods for TransitionEvent { + fn elapsed_time(&self) -> f64 { + self.elapsed_time() + } + fn property_name(&self) -> String { + self.property_name() + } + fn pseudo_element(&self) -> String { + self.pseudo_element() + } + fn as_transition_event(&self) -> &TransitionEvent { + self + } +} +impl EventMethods for TransitionEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/transition_event_init.rs b/bridge/rusty_webf_sys/src/transition_event_init.rs new file mode 100644 index 0000000000..1929805a54 --- /dev/null +++ b/bridge/rusty_webf_sys/src/transition_event_init.rs @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct TransitionEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub elapsed_time: c_double, + pub property_name: *const c_char, + pub pseudo_element: *const c_char, +} diff --git a/bridge/rusty_webf_sys/src/ui_event.rs b/bridge/rusty_webf_sys/src/ui_event.rs new file mode 100644 index 0000000000..b124b2cbad --- /dev/null +++ b/bridge/rusty_webf_sys/src/ui_event.rs @@ -0,0 +1,128 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct UIEventRustMethods { + pub version: c_double, + pub event: *const EventRustMethods, + pub detail: extern "C" fn(ptr: *const OpaquePtr) -> c_double, + pub view: extern "C" fn(ptr: *const OpaquePtr) -> RustValue, + pub which: extern "C" fn(ptr: *const OpaquePtr) -> c_double, +} +pub struct UIEvent { + pub event: Event, + method_pointer: *const UIEventRustMethods, +} +impl UIEvent { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const UIEventRustMethods, status: *const RustValueStatus) -> UIEvent { + unsafe { + UIEvent { + event: Event::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().event, + status, + ), + method_pointer, + } + } + } + pub fn ptr(&self) -> *const OpaquePtr { + self.event.ptr() + } + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.event.context() + } + pub fn detail(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).detail)(self.ptr()) + }; + value + } + pub fn view(&self) -> Window { + let value = unsafe { + ((*self.method_pointer).view)(self.ptr()) + }; + Window::initialize(value.value, self.context(), value.method_pointer, value.status) + } + pub fn which(&self) -> f64 { + let value = unsafe { + ((*self.method_pointer).which)(self.ptr()) + }; + value + } +} +pub trait UIEventMethods: EventMethods { + fn detail(&self) -> f64; + fn view(&self) -> Window; + fn which(&self) -> f64; + fn as_ui_event(&self) -> &UIEvent; +} +impl UIEventMethods for UIEvent { + fn detail(&self) -> f64 { + self.detail() + } + fn view(&self) -> Window { + self.view() + } + fn which(&self) -> f64 { + self.which() + } + fn as_ui_event(&self) -> &UIEvent { + self + } +} +impl EventMethods for UIEvent { + fn bubbles(&self) -> bool { + self.event.bubbles() + } + fn cancel_bubble(&self) -> bool { + self.event.cancel_bubble() + } + fn set_cancel_bubble(&self, value: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.set_cancel_bubble(value, exception_state) + } + fn cancelable(&self) -> bool { + self.event.cancelable() + } + fn current_target(&self) -> EventTarget { + self.event.current_target() + } + fn default_prevented(&self) -> bool { + self.event.default_prevented() + } + fn src_element(&self) -> EventTarget { + self.event.src_element() + } + fn target(&self) -> EventTarget { + self.event.target() + } + fn is_trusted(&self) -> bool { + self.event.is_trusted() + } + fn time_stamp(&self) -> f64 { + self.event.time_stamp() + } + fn type_(&self) -> String { + self.event.type_() + } + fn init_event(&self, type_: &str, bubbles: bool, cancelable: bool, exception_state: &ExceptionState) -> Result<(), String> { + self.event.init_event(type_, bubbles, cancelable, exception_state) + } + fn prevent_default(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.prevent_default(exception_state) + } + fn stop_immediate_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_immediate_propagation(exception_state) + } + fn stop_propagation(&self, exception_state: &ExceptionState) -> Result<(), String> { + self.event.stop_propagation(exception_state) + } + fn as_event(&self) -> &Event { + &self.event + } +} diff --git a/bridge/rusty_webf_sys/src/ui_event_init.rs b/bridge/rusty_webf_sys/src/ui_event_init.rs new file mode 100644 index 0000000000..bad73efe5e --- /dev/null +++ b/bridge/rusty_webf_sys/src/ui_event_init.rs @@ -0,0 +1,16 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; +#[repr(C)] +pub struct UIEventInit { + pub bubbles: i32, + pub cancelable: i32, + pub composed: i32, + pub detail: c_double, + pub view: RustValue, + pub which: c_double, +} diff --git a/bridge/rusty_webf_sys/src/window.rs b/bridge/rusty_webf_sys/src/window.rs new file mode 100644 index 0000000000..938c202c1c --- /dev/null +++ b/bridge/rusty_webf_sys/src/window.rs @@ -0,0 +1,33 @@ +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ + +use std::ffi::c_double; +use crate::event_target::{EventTargetRustMethods, RustMethods}; +use crate::executing_context::ExecutingContext; +use crate::{OpaquePtr, RustValueStatus}; + +#[repr(C)] +pub struct WindowRustMethods { + pub version: c_double, + pub event_target: EventTargetRustMethods, +} + +impl RustMethods for WindowRustMethods {} + +pub struct Window { + ptr: *const OpaquePtr, + method_pointer: *const WindowRustMethods, + status: *const RustValueStatus, +} + + +impl Window { + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const WindowRustMethods, status: *const RustValueStatus) -> Window { + Window { + ptr, + method_pointer, + status, + } + } +} diff --git a/bridge/scripts/code_generator/bin/code_generator.js b/bridge/scripts/code_generator/bin/code_generator.js index ab34c528d6..b9f545e73e 100644 --- a/bridge/scripts/code_generator/bin/code_generator.js +++ b/bridge/scripts/code_generator/bin/code_generator.js @@ -13,6 +13,8 @@ const { generatorSource } = require('../dist/idl/generator') const { generateUnionTypes, generateUnionTypeFileName } = require('../dist/idl/generateUnionTypes') const { generateJSONTemplate } = require('../dist/json/generator'); const { generateNamesInstaller } = require("../dist/json/generator"); +const { generatePluginAPI } = require("../dist/idl/pluginAPIGenerator/cppGen"); +const { generateRustSource } = require("../dist/idl/pluginAPIGenerator/rsGen"); const { union } = require("lodash"); program @@ -170,5 +172,108 @@ let definedPropertyCollector = new DefinedPropertyCollector(); let unionTypeCollector = new UnionTypeCollector(); let names_needs_install = new Set(); +const pluginApiList = [ + 'dom/events/add_event_listener_options.d.ts', + 'dom/events/event_listener_options.d.ts', + 'dom/scroll_options.d.ts', + 'dom/scroll_to_options.d.ts', + 'dom/events/event_init.d.ts', + 'events/animation_event_init.d.ts', + 'events/close_event_init.d.ts', + 'events/focus_event_init.d.ts', + 'events/gesture_event_init.d.ts', + 'events/hashchange_event_init.d.ts', + 'events/input_event_init.d.ts', + 'events/intersection_change_event_init.d.ts', + 'events/keyboard_event_init.d.ts', + 'events/mouse_event_init.d.ts', + 'events/pointer_event_init.d.ts', + 'events/transition_event_init.d.ts', + 'input/touch_init.d.ts', + 'events/ui_event_init.d.ts', + 'dom/events/event.d.ts', + 'dom/events/custom_event.d.ts', + 'events/animation_event.d.ts', + 'events/close_event.d.ts', + 'events/focus_event.d.ts', + 'events/gesture_event.d.ts', + 'events/hashchange_event.d.ts', + 'events/input_event.d.ts', + 'events/intersection_change_event.d.ts', + 'events/mouse_event.d.ts', + 'events/pointer_event.d.ts', + 'events/transition_event.d.ts', + 'events/ui_event.d.ts', +]; + genCodeFromTypeDefine(); genCodeFromJSONData(); +genPluginAPICodeFromTypeDefine(); +genRustCodeFromTypeDefine(); + +function genPluginAPICodeFromTypeDefine() { + // Generate code from type defines. + // let typeFiles = glob.sync("**/*.d.ts", { + // cwd: source, + // }); + + let blobs = pluginApiList.map(file => { + let filename = 'plugin_api_' + file.split('/').slice(-1)[0].replace('.d.ts', ''); + let implement = file.replace(path.join(__dirname, '../../')).replace('.d.ts', ''); + return new IDLBlob(path.join(source, file), dist, filename, implement); + }); + + // Analyze all files first. + for (let i = 0; i < blobs.length; i ++) { + let b = blobs[i]; + analyzer(b, definedPropertyCollector, unionTypeCollector); + } + + for (let i = 0; i < blobs.length; i ++) { + let b = blobs[i]; + let result = generatePluginAPI(b); + + if (!fs.existsSync(b.dist)) { + fs.mkdirSync(b.dist, {recursive: true}); + } + + let headerFilePath = path.join(b.dist, '../include/plugin_api', b.filename.replace('plugin_api_', '')); + let genFilePath = path.join(b.dist, b.filename); + + wirteFileIfChanged(headerFilePath + '.h', result.header); + + if (result.source) { + wirteFileIfChanged(genFilePath + '.cc', result.source); + } + } + +} + +function genRustCodeFromTypeDefine() { + // Generate code from type defines. + let blobs = pluginApiList.map(file => { + let filename = file.split('/').slice(-1)[0].replace('.d.ts', ''); + let implement = file.replace(path.join(__dirname, '../../')).replace('.d.ts', ''); + return new IDLBlob(path.join(source, file), dist, filename, implement); + }); + + // Analyze all files first. + for (let i = 0; i < blobs.length; i ++) { + let b = blobs[i]; + analyzer(b, definedPropertyCollector, unionTypeCollector); + } + + for (let i = 0; i < blobs.length; i ++) { + let b = blobs[i]; + let result = generateRustSource(b); + + if (!fs.existsSync(b.dist)) { + fs.mkdirSync(b.dist, {recursive: true}); + } + + let genFilePath = path.join(b.dist, '../rusty_webf_sys/src', b.filename); + + wirteFileIfChanged(genFilePath + '.rs', result); + } + +} diff --git a/bridge/scripts/code_generator/global.d.ts b/bridge/scripts/code_generator/global.d.ts index d34b2abc9a..383e88d57d 100644 --- a/bridge/scripts/code_generator/global.d.ts +++ b/bridge/scripts/code_generator/global.d.ts @@ -14,6 +14,7 @@ declare type LegacyNullToEmptyString = string | null; // This property is implemented by Dart side type DartImpl = T; type StaticMember = T; +type StaticMethod = T; type DependentsOnLayout = T; \ No newline at end of file diff --git a/bridge/scripts/code_generator/src/idl/analyzer.ts b/bridge/scripts/code_generator/src/idl/analyzer.ts index 6e0ae6d27a..44597be706 100644 --- a/bridge/scripts/code_generator/src/idl/analyzer.ts +++ b/bridge/scripts/code_generator/src/idl/analyzer.ts @@ -149,6 +149,11 @@ function getParameterBaseType(type: ts.TypeNode, mode?: ParameterMode): Paramete let argument = typeReference.typeArguments![0]; // @ts-ignore return getParameterBaseType(argument); + } else if (identifier === 'StaticMethod') { + if (mode) mode.staticMethod = true; + let argument = typeReference.typeArguments![0]; + // @ts-ignore + return getParameterBaseType(argument); } else if (identifier === 'LegacyNullToEmptyString') { return FunctionArgumentType.legacy_dom_string; } diff --git a/bridge/scripts/code_generator/src/idl/declaration.ts b/bridge/scripts/code_generator/src/idl/declaration.ts index 2bb628d8f8..2bd2517053 100644 --- a/bridge/scripts/code_generator/src/idl/declaration.ts +++ b/bridge/scripts/code_generator/src/idl/declaration.ts @@ -34,6 +34,7 @@ export class ParameterMode { dartImpl?: boolean; layoutDependent?: boolean; static?: boolean; + staticMethod?: boolean; } export class PropsDeclaration { @@ -62,7 +63,7 @@ export enum ClassObjectKind { } export class ClassObject { - static globalClassMap = new Map(); + static globalClassMap: {[key: string]: ClassObject} = Object.create(null); name: string; parent: string; mixinParent: string[]; diff --git a/bridge/scripts/code_generator/src/idl/generateSource.ts b/bridge/scripts/code_generator/src/idl/generateSource.ts index 128fde764d..93d5d3c8f2 100644 --- a/bridge/scripts/code_generator/src/idl/generateSource.ts +++ b/bridge/scripts/code_generator/src/idl/generateSource.ts @@ -148,14 +148,18 @@ export function isTypeHaveNull(type: ParameterType): boolean { return type.value.some(t => t.value === FunctionArgumentType.null); } -export function isTypeHaveString(types: ParameterType[]): boolean { - return types.some(t => { - if (t.isArray) return isTypeHaveString(t.value as ParameterType[]); - if (!Array.isArray(t.value)) { - return t.value === FunctionArgumentType.dom_string; - } - return t.value.some(t => t.value === FunctionArgumentType.dom_string); - }); +export function isTypeHaveString(types: ParameterType[] | ParameterType): boolean { + if (Array.isArray(types)) { + return types.some(t => { + if (t.isArray) return isTypeHaveString(t.value as ParameterType); + if (!Array.isArray(t.value)) { + return t.value === FunctionArgumentType.dom_string; + } + return t.value.some(t => t.value === FunctionArgumentType.dom_string); + }); + } + + return types.value === FunctionArgumentType.dom_string; } export function isPointerType(type: ParameterType): boolean { diff --git a/bridge/scripts/code_generator/src/idl/generator.ts b/bridge/scripts/code_generator/src/idl/generator.ts index 576f63c91f..7499721da0 100644 --- a/bridge/scripts/code_generator/src/idl/generator.ts +++ b/bridge/scripts/code_generator/src/idl/generator.ts @@ -2,7 +2,7 @@ import {IDLBlob} from './IDLBlob'; import {generateCppHeader} from "./generateHeader"; import {generateCppSource} from "./generateSource"; -function generateSupportedOptions(): GenerateOptions { +export function generateSupportedOptions(): GenerateOptions { let globalFunctionInstallList: string[] = []; let classMethodsInstallList: string[] = []; let constructorInstallList: string[] = []; diff --git a/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/cppGen.ts b/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/cppGen.ts new file mode 100644 index 0000000000..b3c4f39fc9 --- /dev/null +++ b/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/cppGen.ts @@ -0,0 +1,337 @@ +import fs from 'fs'; +import path from 'path'; +import {IDLBlob} from '../IDLBlob'; +import {getTemplateKind, TemplateKind} from '../generateHeader'; +import _ from 'lodash'; +import {ClassObject, FunctionArguments, FunctionArgumentType} from '../declaration'; +import {GenerateOptions, generateSupportedOptions} from '../generator'; +import {ParameterType} from '../analyzer'; +import {getPointerType, isPointerType} from '../generateSource'; + +function readHeaderTemplate(name: string) { + return fs.readFileSync(path.join(__dirname, '../../../templates/idl_templates/plugin_api_templates/' + name + '.h.tpl'), {encoding: 'utf-8'}); +} + +function readSourceTemplate(name: string) { + return fs.readFileSync(path.join(__dirname, '../../../templates/idl_templates/plugin_api_templates/' + name + '.cc.tpl'), {encoding: 'utf-8'}); +} + +function getClassName(blob: IDLBlob) { + let raw = _.camelCase(blob.filename[11].toUpperCase() + blob.filename.slice(12)); + if (raw.slice(0, 3) == 'dom') { + return 'DOM' + raw.slice(3); + } + if (raw.slice(0, 4) == 'html') { + // Legacy support names. + if (raw === 'htmlIframeElement') { + return `HTMLIFrameElement`; + } + return 'HTML' + raw.slice(4); + } + if (raw.slice(0, 6) == 'svgSvg') { + // special for SVGSVGElement + return 'SVGSVG' + raw.slice(6) + } + if (raw.slice(0, 3) == 'svg') { + return 'SVG' + raw.slice(3) + } + if (raw.slice(0, 3) == 'css') { + return 'CSS' + raw.slice(3); + } + if (raw.slice(0, 2) == 'ui') { + return 'UI' + raw.slice(2); + } + + return `${raw[0].toUpperCase() + raw.slice(1)}`; +} + +export function isStringType(type: ParameterType): boolean { + return type.value === FunctionArgumentType.dom_string + || type.value === FunctionArgumentType.legacy_dom_string; +} + +function generatePublicReturnTypeValue(type: ParameterType, is32Bit: boolean = false): string { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `WebFValue<${pointerType}, ${pointerType}PublicMethods>`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'int64_t'; + } + case FunctionArgumentType.int32: { + return 'int64_t'; + } + case FunctionArgumentType.double: { + return 'double'; + } + case FunctionArgumentType.boolean: { + return 'int32_t'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + if (is32Bit) { + return 'const char*'; + } + + return 'SharedNativeString*'; + } + case FunctionArgumentType.any: { + return 'WebFValue'; + } + case FunctionArgumentType.void: + return 'void'; + default: + if (is32Bit) { + return 'int64_t'; + } + return 'void*'; + } +} + +function generatePublicParameterType(type: ParameterType, is32Bit: boolean = false): string { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + // dictionary types + if (pointerType.endsWith('Options') || pointerType.endsWith('Init')) { + return `WebF${pointerType}*`; + } + // special case for EventListener + else if (pointerType === 'JSEventListener') { + return 'WebFEventListenerContext*'; + } + return `${pointerType}*`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'int64_t'; + } + case FunctionArgumentType.int32: { + return 'int64_t'; + } + case FunctionArgumentType.double: { + return 'double'; + } + case FunctionArgumentType.boolean: { + return 'int32_t'; + } + case FunctionArgumentType.any: { + return 'ScriptValueRef*'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + if (is32Bit) { + return 'const char*'; + } + + return 'SharedNativeString*'; + } + default: + if (is32Bit) { + return 'int64_t'; + } + return 'void*'; + } +} + +function generatePublicParametersType(parameters: FunctionArguments[], is32Bit: boolean = false): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generatePublicParameterType(param.type, is32Bit)}`; + }).join(', ') + ', '; +} + +function generatePublicParametersTypeWithName(parameters: FunctionArguments[], is32Bit: boolean = false): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generatePublicParameterType(param.type, is32Bit)} ${_.snakeCase(param.name)}`; + }).join(', ') + ', '; +} + +function generatePublicParametersName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + const name = _.snakeCase(param.name); + return `${isStringType(param.type) ? name + '_atomic' : name}`; + }).join(', ') + ', '; +} + +export function isAnyType(type: ParameterType): boolean { + return type.value === FunctionArgumentType.any; +} + +function generatePluginAPIHeaderFile(blob: IDLBlob, options: GenerateOptions) { + const baseTemplate = readHeaderTemplate('base'); + const contents = blob.objects.map(object => { + const templateKind = getTemplateKind(object); + if (templateKind === TemplateKind.null) { + return ''; + } + + switch(templateKind) { + case TemplateKind.Interface: { + object = object as ClassObject; + + let dependentTypes = new Set(); + + object.props.forEach(prop => { + if (isPointerType(prop.type)) { + dependentTypes.add(getPointerType(prop.type)); + } + }); + + object.methods.forEach(method => { + method.args.forEach(param => { + if (isPointerType(param.type)) { + dependentTypes.add(getPointerType(param.type)); + } + }); + if (isPointerType(method.returnType)) { + dependentTypes.add(getPointerType(method.returnType)); + } + }); + + return _.template(readHeaderTemplate('interface'))({ + className: getClassName(blob), + parentClassName: object.parent, + blob: blob, + object, + generatePublicReturnTypeValue, + generatePublicParametersType, + generatePublicParametersTypeWithName, + isStringType, + dependentTypes: Array.from(dependentTypes), + options, + }); + } + case TemplateKind.Dictionary: { + object = object as ClassObject; + + let dependentTypes = new Set(); + + object.props.forEach(prop => { + if (isPointerType(prop.type)) { + dependentTypes.add(getPointerType(prop.type)); + } + }); + + const parentObject = ClassObject.globalClassMap[object.parent]; + + if (parentObject) { + parentObject.props.forEach(prop => { + if (isPointerType(prop.type)) { + dependentTypes.add(getPointerType(prop.type)); + } + }); + } + + return _.template(readHeaderTemplate('dictionary'))({ + className: getClassName(blob), + parentClassName: object.parent, + parentObject, + blob: blob, + object, + generatePublicReturnTypeValue, + isStringType, + dependentTypes: Array.from(dependentTypes), + options, + }); + } + case TemplateKind.globalFunction: { + return ''; + } + } + }); + + return _.template(baseTemplate)({ + content: contents.join('\n'), + blob: blob + }).split('\n').filter(str => { + return str.trim().length > 0; + }).join('\n') + '\n'; +} + +function generatePluginAPISourceFile(blob: IDLBlob, options: GenerateOptions) { + const baseTemplate = readSourceTemplate('base'); + const contents = blob.objects.map(object => { + const templateKind = getTemplateKind(object); + if (templateKind === TemplateKind.null || templateKind === TemplateKind.Dictionary) { + return ''; + } + + switch(templateKind) { + case TemplateKind.Interface: { + object = object as ClassObject; + + let dependentTypes = new Set(); + + object.props.forEach(prop => { + if (isPointerType(prop.type)) { + dependentTypes.add(getPointerType(prop.type)); + } + }); + + object.methods.forEach(method => { + method.args.forEach(param => { + if (isPointerType(param.type)) { + dependentTypes.add(getPointerType(param.type)); + } + }); + if (isPointerType(method.returnType)) { + dependentTypes.add(getPointerType(method.returnType)); + } + }); + + return _.template(readSourceTemplate('interface'))({ + className: getClassName(blob), + parentClassName: object.parent, + blob: blob, + object, + generatePublicReturnTypeValue, + generatePublicParametersType, + generatePublicParametersTypeWithName, + generatePublicParametersName, + generatePublicParameterType, + isPointerType, + getPointerType, + isStringType, + isAnyType, + dependentTypes: Array.from(dependentTypes), + options, + }); + } + case TemplateKind.globalFunction: { + return ''; + } + } + }).filter(str => str.trim().length > 0); + + if (contents.length === 0) { + return ''; + } + + return _.template(baseTemplate)({ + content: contents.join('\n'), + blob: blob + }).split('\n').filter(str => { + return str.trim().length > 0; + }).join('\n') + '\n'; +} + +export function generatePluginAPI(blob: IDLBlob) { + let options = generateSupportedOptions(); + + const header = generatePluginAPIHeaderFile(blob, options); + const source = generatePluginAPISourceFile(blob, options); + + return { + header, + source + }; +} diff --git a/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/rsGen.ts b/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/rsGen.ts new file mode 100644 index 0000000000..e6e79eb8d0 --- /dev/null +++ b/bridge/scripts/code_generator/src/idl/pluginAPIGenerator/rsGen.ts @@ -0,0 +1,374 @@ +import fs from 'fs'; +import path from 'path'; +import _ from 'lodash'; +import {getTemplateKind, TemplateKind} from '../generateHeader'; +import {GenerateOptions, generateSupportedOptions} from '../generator'; +import {IDLBlob} from '../IDLBlob'; +import {ClassObject, FunctionArguments, FunctionArgumentType} from '../declaration'; +import {getPointerType, isPointerType} from '../generateSource'; +import {ParameterType} from '../analyzer'; +import {isAnyType, isStringType} from './cppGen'; + +function readSourceTemplate(name: string) { + return fs.readFileSync(path.join(__dirname, '../../../templates/idl_templates/plugin_api_templates/' + name + '.rs.tpl'), {encoding: 'utf-8'}); +} + +function isVoidType(type: ParameterType) { + return type.value === FunctionArgumentType.void; +} + +function generatePublicReturnTypeValue(type: ParameterType) { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `RustValue<${pointerType}RustMethods>`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'i64'; + } + case FunctionArgumentType.int32: { + return 'i64'; + } + case FunctionArgumentType.double: { + return 'c_double'; + } + case FunctionArgumentType.any: { + return 'RustValue'; + } + case FunctionArgumentType.boolean: { + return 'i32'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return '*const c_char'; + } + case FunctionArgumentType.void: + return 'c_void'; + default: + return 'void*'; + } +} + +function generateMethodReturnType(type: ParameterType) { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `${pointerType}`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'i64'; + } + case FunctionArgumentType.int32: { + return 'i64'; + } + case FunctionArgumentType.any: { + return 'ScriptValueRef'; + } + case FunctionArgumentType.double: { + return 'f64'; + } + case FunctionArgumentType.boolean: { + return 'bool'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return 'String'; + } + case FunctionArgumentType.void: + return '()'; + default: + return 'void*'; + } +} + +function generatePublicParameterType(type: ParameterType): string { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `${pointerType}*`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'i64'; + } + case FunctionArgumentType.int32: { + return 'i64'; + } + case FunctionArgumentType.double: { + return 'c_double'; + } + case FunctionArgumentType.any: { + return '*const OpaquePtr'; + } + case FunctionArgumentType.boolean: { + return 'i32'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return '*const c_char'; + } + default: + return 'void*'; + } +} + +function generatePublicParametersType(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generatePublicParameterType(param.type)}`; + }).join(', ') + ', '; +} + +function generatePublicParametersTypeWithName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generatePublicParameterType(param.type)} ${param.name}`; + }).join(', ') + ', '; +} + +function generatePublicParametersName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${param.name}`; + }).join(', ') + ', '; +} + +function generateMethodParameterType(type: ParameterType): string { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `${pointerType}*`; + } + switch (type.value) { + case FunctionArgumentType.int64: { + return 'i64'; + } + case FunctionArgumentType.int32: { + return 'i64'; + } + case FunctionArgumentType.double: { + return 'f64'; + } + case FunctionArgumentType.any: { + return '&ScriptValueRef'; + } + case FunctionArgumentType.boolean: { + return 'bool'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return '&str'; + } + default: + return 'void*'; + } +} + +function generateMethodParametersType(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generateMethodParameterType(param.type)}`; + }).join(', ') + ', '; +} + +function generateMethodParametersTypeWithName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generateValidRustIdentifier(param.name)}: ${generateMethodParameterType(param.type)}`; + }).join(', ') + ', '; +} + +function generateMethodParametersName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + switch (param.type.value) { + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return `CString::new(${generateValidRustIdentifier(param.name)}).unwrap().as_ptr()`; + } + case FunctionArgumentType.boolean: { + return `i32::from(${generateValidRustIdentifier(param.name)})`; + } + case FunctionArgumentType.any: + return `${param.name}.ptr`; + default: + return `${generateValidRustIdentifier(param.name)}`; + } + }).join(', ') + ', '; +} + +function generateParentMethodParametersName(parameters: FunctionArguments[]): string { + if (parameters.length === 0) { + return ''; + } + return parameters.map(param => { + return `${generateValidRustIdentifier(param.name)}`; + }).join(', ') + ', '; +} + +function getClassName(blob: IDLBlob) { + let raw = _.camelCase(blob.filename[0].toUpperCase() + blob.filename.slice(1)); + if (raw.slice(0, 3) == 'dom') { + return 'DOM' + raw.slice(3); + } + if (raw.slice(0, 4) == 'html') { + // Legacy support names. + if (raw === 'htmlIframeElement') { + return `HTMLIFrameElement`; + } + return 'HTML' + raw.slice(4); + } + if (raw.slice(0, 6) == 'svgSvg') { + // special for SVGSVGElement + return 'SVGSVG' + raw.slice(6) + } + if (raw.slice(0, 3) == 'svg') { + return 'SVG' + raw.slice(3) + } + if (raw.slice(0, 3) == 'css') { + return 'CSS' + raw.slice(3); + } + if (raw.slice(0, 2) == 'ui') { + return 'UI' + raw.slice(2); + } + + return `${raw[0].toUpperCase() + raw.slice(1)}`; +} + +function generateValidRustIdentifier(name: string) { + const rustKeywords = [ + 'type', + ]; + return rustKeywords.includes(name) ? `${name}_` : name; +} + +function generateMethodReturnStatements(type: ParameterType) { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `Ok(${pointerType}::initialize(value.value, self.context(), value.method_pointer, value.status))`; + } + switch (type.value) { + case FunctionArgumentType.boolean: { + return 'Ok(value != 0)'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return `let value = unsafe { std::ffi::CStr::from_ptr(value) }; + Ok(value.to_str().unwrap().to_string())`; + } + default: + return 'Ok(value)'; + } +} + +function generatePropReturnStatements(type: ParameterType) { + if (isPointerType(type)) { + const pointerType = getPointerType(type); + return `${pointerType}::initialize(value.value, self.context(), value.method_pointer, value.status)`; + } + switch (type.value) { + case FunctionArgumentType.boolean: { + return 'value != 0'; + } + case FunctionArgumentType.dom_string: + case FunctionArgumentType.legacy_dom_string: { + return `let value = unsafe { std::ffi::CStr::from_ptr(value) }; + value.to_str().unwrap().to_string()`; + } + case FunctionArgumentType.any: { + return `ScriptValueRef { + ptr: value.value, + method_pointer: value.method_pointer + }`; + } + default: + return 'value'; + } +} + +function generateRustSourceFile(blob: IDLBlob, options: GenerateOptions) { + const baseTemplate = readSourceTemplate('base'); + const contents = blob.objects.map(object => { + const templateKind = getTemplateKind(object); + if (templateKind === TemplateKind.null) return ''; + + switch(templateKind) { + case TemplateKind.Interface: { + object = object as ClassObject; + + const inheritedObjects: ClassObject[] = []; + + let currentParentObject = object; + while (currentParentObject.parent) { + const parentObject = ClassObject.globalClassMap[currentParentObject.parent]; + inheritedObjects.push(parentObject); + currentParentObject = parentObject; + } + + return _.template(readSourceTemplate('interface'))({ + className: getClassName(blob), + parentClassName: object.parent, + blob, + object, + inheritedObjects, + isPointerType, + generatePublicReturnTypeValue, + generatePublicParametersType, + generatePublicParametersTypeWithName, + generateMethodReturnType, + generateMethodParametersTypeWithName, + generateMethodParametersName, + generateParentMethodParametersName, + generateMethodReturnStatements, + generatePropReturnStatements, + generateValidRustIdentifier, + isVoidType, + options, + }); + } + case TemplateKind.Dictionary: { + object = object as ClassObject; + const parentObject = ClassObject.globalClassMap[object.parent]; + + return _.template(readSourceTemplate('dictionary'))({ + className: getClassName(blob), + parentClassName: object.parent, + parentObject, + blob, + object, + generatePublicReturnTypeValue, + isStringType, + options, + }); + } + case TemplateKind.globalFunction: { + return ''; + } + } + }); + + return _.template(baseTemplate)({ + content: contents.join('\n'), + blob: blob + }).split('\n').filter(str => { + return str.trim().length > 0; + }).join('\n') + '\n'; +} + +export function generateRustSource(blob: IDLBlob) { + let options = generateSupportedOptions(); + + const source = generateRustSourceFile(blob, options); + + return source; +} diff --git a/bridge/scripts/code_generator/templates/idl_templates/interface.cc.tpl b/bridge/scripts/code_generator/templates/idl_templates/interface.cc.tpl index a4f6c9e094..fa62c5be51 100644 --- a/bridge/scripts/code_generator/templates/idl_templates/interface.cc.tpl +++ b/bridge/scripts/code_generator/templates/idl_templates/interface.cc.tpl @@ -137,7 +137,7 @@ JSValue QJS<%= className %>::ConstructorCallback(JSContext* ctx, JSValue func_ob return success; }; <% } %> - <% } %> +<% } %> <% _.forEach(filtedMethods, function(method, index) { %> @@ -200,6 +200,10 @@ static JSValue <%= prop.name %>AttributeGetCallback(JSContext* ctx, JSValueConst auto result = Converter<<%= generateIDLTypeConverter(prop.type, prop.optional) %>>::ToValue(ctx, <%= className %>::<%= prop.name %>); context->dartIsolateContext()->profiler()->FinishTrackSteps(); return result; + <% } else if (prop.typeMode && prop.typeMode.staticMethod) { %> + auto result = Converter<<%= generateIDLTypeConverter(prop.type, prop.optional) %>>::ToValue(ctx, <%= className %>::<%= prop.name %>()); + context->dartIsolateContext()->profiler()->FinishTrackSteps(); + return result; <% } else { %> auto result = Converter<<%= generateIDLTypeConverter(prop.type, prop.optional) %>>::ToValue(ctx, <%= blob.filename %>-><%= prop.name %>()); context->dartIsolateContext()->profiler()->FinishTrackSteps(); diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.cc.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.cc.tpl new file mode 100644 index 0000000000..a48fb51977 --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.cc.tpl @@ -0,0 +1,29 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off + +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#include "plugin_api/<%= blob.filename.replace('plugin_api_', '') %>.h" +#include "plugin_api/event_target.h" +#include "plugin_api/exception_state.h" +#include "core/dom/events/event.h" +#include "core/dom/events/custom_event.h" +#include "core/native/script_value_ref.h" +#include "core/dom/events/event_target.h" +#include "core/events/animation_event.h" +#include "core/events/close_event.h" +#include "core/events/focus_event.h" +#include "core/events/gesture_event.h" +#include "core/events/hashchange_event.h" +#include "core/events/input_event.h" +#include "core/events/intersection_change_event.h" +#include "core/events/mouse_event.h" +#include "core/api/exception_state.h" +#include "core/events/pointer_event.h" +#include "core/events/transition_event.h" +#include "core/events/ui_event.h" + +<%= content %> diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.h.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.h.tpl new file mode 100644 index 0000000000..ed3a885e2f --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.h.tpl @@ -0,0 +1,14 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js +// clang-format off + +/* + * Copyright (C) 2022-present The WebF authors. All rights reserved. + */ + +#ifndef WEBF_CORE_WEBF_API_<%= blob.filename.toUpperCase() %>_H_ +#define WEBF_CORE_WEBF_API_<%= blob.filename.toUpperCase() %>_H_ +#include +<%= content %> + +#endif // WEBF_CORE_WEBF_API_<%= blob.filename.toUpperCase() %>_H_ diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.rs.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.rs.tpl new file mode 100644 index 0000000000..4817359dba --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/base.rs.tpl @@ -0,0 +1,10 @@ +// Generated by WebF TSDL, don't edit this file directly. +// Generate command: node scripts/generate_binding_code.js + +/* +* Copyright (C) 2022-present The WebF authors. All rights reserved. +*/ +use std::ffi::*; +use crate::*; + +<%= content %> diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.h.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.h.tpl new file mode 100644 index 0000000000..efdfaa8687 --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.h.tpl @@ -0,0 +1,37 @@ +#include "webf_value.h" + +namespace webf { + +<% _.forEach(dependentTypes, function (dependentType) { %> + <% if (dependentType.endsWith('Options') || dependentType.endsWith('Init')) { %> + <% } else if (dependentType === 'JSEventListener') { %> + <% } else { %> +typedef struct <%= dependentType %> <%= dependentType %>; +typedef struct <%= dependentType %>PublicMethods <%= dependentType %>PublicMethods; + <% } %> +<% }); %> + +struct WebF<%= className %> { +<% if (parentObject?.props) { %> + <% _.forEach(parentObject.props, function(prop, index) { %> + <% if (isStringType(prop.type)) { %> + <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } else if (prop.readonly) { %> + const <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } else { %> + <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } %> + <% }); %> +<% } %> +<% _.forEach(object.props, function(prop, index) { %> + <% if (isStringType(prop.type)) { %> + <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } else if (prop.readonly) { %> + const <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } else { %> + <%= generatePublicReturnTypeValue(prop.type, true) %> <%= _.snakeCase(prop.name) %>; + <% } %> +<% }); %> +}; + +} // namespace webf diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.rs.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.rs.tpl new file mode 100644 index 0000000000..71d20dc22c --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/dictionary.rs.tpl @@ -0,0 +1,21 @@ +#[repr(C)] +pub struct <%= className %> { +<% if (parentObject?.props) { %> + <% _.forEach(parentObject.props, function(prop, index) { %> + <% var propName = _.snakeCase(prop.name) %> + <% if (isStringType(prop.type)) { %> + pub <%= propName %>: <%= generatePublicReturnTypeValue(prop.type, true) %>, + <% } else { %> + pub <%= propName %>: <%= generatePublicReturnTypeValue(prop.type, true) %>, + <% } %> + <% }); %> +<% } %> +<% _.forEach(object.props, function(prop, index) { %> + <% var propName = _.snakeCase(prop.name) %> + <% if (isStringType(prop.type)) { %> + pub <%= propName %>: <%= generatePublicReturnTypeValue(prop.type, true) %>, + <% } else { %> + pub <%= propName %>: <%= generatePublicReturnTypeValue(prop.type, true) %>, + <% } %> +<% }); %> +} diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.cc.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.cc.tpl new file mode 100644 index 0000000000..1381cf21f6 --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.cc.tpl @@ -0,0 +1,49 @@ +namespace webf { + +<% _.forEach(object.props, function(prop, index) { %> +<%= generatePublicReturnTypeValue(prop.type, true) %> <%= className %>PublicMethods::<%= _.startCase(prop.name).replace(/ /g, '') %>(<%= className %>* <%= _.snakeCase(className) %>) { + <% if (isPointerType(prop.type)) { %> + auto* result = <%= _.snakeCase(className) %>-><%= prop.name %>(); + WebFValueStatus* status_block = result->KeepAlive(); + return <%= generatePublicReturnTypeValue(prop.type, true) %>(result, result-><%= _.camelCase(getPointerType(prop.type)) %>PublicMethods(), status_block); + <% } else if (isAnyType(prop.type)) { %> + return WebFValue{ + new ScriptValueRef{<%= _.snakeCase(className) %>->GetExecutingContext(), <%= _.snakeCase(className) %>-><%= prop.name %>()}, ScriptValueRef::publicMethods(), + nullptr}; + <% } else if (isStringType(prop.type)) { %> + return <%= _.snakeCase(className) %>-><%= prop.name %>().ToStringView().Characters8(); + <% } else { %> + return <%= _.snakeCase(className) %>-><%= prop.name %>(); + <% } %> +} + <% if (!prop.readonly) { %> +void <%= className %>PublicMethods::Set<%= _.startCase(prop.name).replace(/ /g, '') %>(<%= className %>* <%= _.snakeCase(className) %>, <%= generatePublicReturnTypeValue(prop.type, true) %> <%= prop.name %>, SharedExceptionState* shared_exception_state) { + <%= _.snakeCase(className) %>->set<%= _.startCase(prop.name).replace(/ /g, '') %>(<%= prop.name %>, shared_exception_state->exception_state); +} + <% } %> + <% if (isStringType(prop.type)) { %> +<%= generatePublicReturnTypeValue(prop.type, true) %> <%= className %>PublicMethods::Dup<%= _.startCase(prop.name).replace(/ /g, '') %>(<%= className %>* <%= _.snakeCase(className) %>) { + const char* buffer = <%= _.snakeCase(className) %>-><%= prop.name %>().ToStringView().Characters8(); + return strdup(buffer); +} + <% } %> +<% }); %> + +<% _.forEach(object.methods, function(method, index) { %> +<%= generatePublicReturnTypeValue(method.returnType, true) %> <%= className %>PublicMethods::<%= _.startCase(method.name).replace(/ /g, '') %>(<%= className %>* <%= _.snakeCase(className) %>, <%= generatePublicParametersTypeWithName(method.args, true) %>SharedExceptionState* shared_exception_state) { + <% _.forEach(method.args, function(arg, index) { %> + <% if (isStringType(arg.type)) { %> + webf::AtomicString <%= _.snakeCase(arg.name) %>_atomic = webf::AtomicString(<%= _.snakeCase(className) %>->ctx(), <%= _.snakeCase(arg.name) %>); + <% } %> + <% }); %> + return <%= _.snakeCase(className) %>-><%= method.name %>(<%= generatePublicParametersName(method.args) %>shared_exception_state->exception_state); +} +<% }); %> + +<% if (!object.parent) { %> +void <%= className %>PublicMethods::Release(<%= className %>* <%= _.snakeCase(className) %>) { + <%= _.snakeCase(className) %>->ReleaseAlive(); +} +<% } %> + +} // namespace webf diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.h.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.h.tpl new file mode 100644 index 0000000000..a6c6852bce --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.h.tpl @@ -0,0 +1,93 @@ +#include "script_value_ref.h" +<% if (object.parent) { %> +#include "<%= _.snakeCase(object.parent) %>.h" +<% } else { %> +#include "webf_value.h" +<% } %> + +namespace webf { + +<% _.forEach(dependentTypes, function (dependentType) { %> + <% if (dependentType.endsWith('Options') || dependentType.endsWith('Init')) { %> +typedef struct WebF<%= dependentType %> WebF<%= dependentType %>; + <% } else if (dependentType === 'JSEventListener') { %> +typedef struct WebFEventListenerContext WebFEventListenerContext; + <% } else { %> +class <%= dependentType %>; +typedef struct <%= dependentType %>PublicMethods <%= dependentType %>PublicMethods; + <% } %> +<% }); %> +class SharedExceptionState; +class ExecutingContext; +class <%= className %>; +typedef struct ScriptValueRef ScriptValueRef; + +<% _.forEach(object.props, function(prop, index) { %> + <% var propName = _.startCase(prop.name).replace(/ /g, ''); %> +using Public<%= className %>Get<%= propName %> = <%= generatePublicReturnTypeValue(prop.type, true) %> (*)(<%= className %>*); + <% if (!prop.readonly) { %> +using Public<%= className %>Set<%= propName %> = void (*)(<%= className %>*, <%= generatePublicReturnTypeValue(prop.type, true) %>, SharedExceptionState*); + <% } %> + <% if (isStringType(prop.type)) { %> +using Public<%= className %>Dup<%= propName %> = <%= generatePublicReturnTypeValue(prop.type, true) %> (*)(<%= className %>*); + <% } %> +<% }); %> + +<% _.forEach(object.methods, function(method, index) { %> + <% var methodName = _.startCase(method.name).replace(/ /g, ''); %> +using Public<%= className %><%= methodName %> = <%= generatePublicReturnTypeValue(method.returnType, true) %> (*)(<%= className %>*, <%= generatePublicParametersType(method.args, true) %>SharedExceptionState*); +<% }); %> + +<% if (!object.parent) { %> +using Public<%= className %>Release = void (*)(<%= className %>*); +<% } %> + +struct <%= className %>PublicMethods : public WebFPublicMethods { + + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = _.startCase(prop.name).replace(/ /g, ''); %> + static <%= generatePublicReturnTypeValue(prop.type, true) %> <%= propName %>(<%= className %>* <%= _.snakeCase(className) %>); + <% if (!prop.readonly) { %> + static void Set<%= propName %>(<%= className %>* <%= _.snakeCase(className) %>, <%= generatePublicReturnTypeValue(prop.type, true) %> <%= prop.name %>, SharedExceptionState* shared_exception_state); + <% } %> + <% if (isStringType(prop.type)) { %> + static <%= generatePublicReturnTypeValue(prop.type, true) %> Dup<%= propName %>(<%= className %>* <%= _.snakeCase(className) %>); + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = _.startCase(method.name).replace(/ /g, ''); %> + static <%= generatePublicReturnTypeValue(method.returnType, true) %> <%= methodName %>(<%= className %>* <%= _.snakeCase(className) %>, <%= generatePublicParametersTypeWithName(method.args, true) %>SharedExceptionState* shared_exception_state); + <% }); %> + + <% if (!object.parent) { %> + static void Release(<%= className %>* <%= _.snakeCase(className) %>); + <% } %> + double version{1.0}; + + <% if (object.parent) { %> + <%= object.parent %>PublicMethods <%= _.snakeCase(object.parent) %>; + <% } %> + + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = _.startCase(prop.name).replace(/ /g, ''); %> + Public<%= className %>Get<%= propName %> <%= _.snakeCase(className) %>_get_<%= _.snakeCase(prop.name) %>{<%= propName %>}; + <% if (!prop.readonly) { %> + Public<%= className %>Set<%= propName %> <%= _.snakeCase(className) %>_set_<%= _.snakeCase(prop.name) %>{Set<%= propName %>}; + <% } %> + <% if (isStringType(prop.type)) { %> + Public<%= className %>Dup<%= propName %> <%= _.snakeCase(className) %>_dup_<%= _.snakeCase(prop.name) %>{Dup<%= propName %>}; + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = _.startCase(method.name).replace(/ /g, ''); %> + Public<%= className %><%= methodName %> <%= _.snakeCase(className) %>_<%= _.snakeCase(method.name) %>{<%= methodName %>}; + <% }); %> + + <% if (!object.parent) { %> + Public<%= className %>Release <%= _.snakeCase(className) %>_release{Release}; + <% } %> +}; + +} // namespace webf diff --git a/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.rs.tpl b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.rs.tpl new file mode 100644 index 0000000000..5ed63a0836 --- /dev/null +++ b/bridge/scripts/code_generator/templates/idl_templates/plugin_api_templates/interface.rs.tpl @@ -0,0 +1,253 @@ +#[repr(C)] +pub struct <%= className %>RustMethods { + pub version: c_double, + <% if (object.parent) { %> + pub <%= _.snakeCase(object.parent) %>: *const <%= object.parent %>RustMethods, + <% } %> + + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = generateValidRustIdentifier(_.snakeCase(prop.name)); %> + pub <%= propName %>: extern "C" fn(ptr: *const OpaquePtr) -> <%= generatePublicReturnTypeValue(prop.type) %>, + <% if (!prop.readonly) { %> + pub set_<%= _.snakeCase(prop.name) %>: extern "C" fn(ptr: *const OpaquePtr, value: <%= generatePublicReturnTypeValue(prop.type) %>, exception_state: *const OpaquePtr) -> bool, + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = generateValidRustIdentifier(_.snakeCase(method.name)); %> + pub <%= methodName %>: extern "C" fn(ptr: *const OpaquePtr, <%= generatePublicParametersType(method.args) %>exception_state: *const OpaquePtr) -> <%= generatePublicReturnTypeValue(method.returnType) %>, + <% }); %> + + <% if (!object.parent) { %> + pub release: extern "C" fn(ptr: *const OpaquePtr) -> c_void, + <% } %> +} + +<% if (object.parent) { %> +pub struct <%= className %> { + pub <%= _.snakeCase(object.parent) %>: <%= object.parent %>, + method_pointer: *const <%= className %>RustMethods, +} +<% } else { %> +pub struct <%= className %> { + pub ptr: *const OpaquePtr, + context: *const ExecutingContext, + method_pointer: *const <%= className %>RustMethods, + status: *const RustValueStatus +} +<% } %> + +impl <%= className %> { + <% if (object.parent) { %> + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const <%= className %>RustMethods, status: *const RustValueStatus) -> <%= className %> { + unsafe { + <%= className %> { + <%= _.snakeCase(object.parent) %>: <%= object.parent %>::initialize( + ptr, + context, + method_pointer.as_ref().unwrap().<%= _.snakeCase(object.parent) %>, + status, + ), + method_pointer, + } + } + } + + pub fn ptr(&self) -> *const OpaquePtr { + self.<%= _.snakeCase(object.parent) %>.ptr() + } + + pub fn context<'a>(&self) -> &'a ExecutingContext { + self.<%= _.snakeCase(object.parent) %>.context() + } + + <% } else { %> + pub fn initialize(ptr: *const OpaquePtr, context: *const ExecutingContext, method_pointer: *const <%= className %>RustMethods, status: *const RustValueStatus) -> <%= className %> { + <%= className %> { + ptr, + context, + method_pointer, + status + } + } + + pub fn ptr(&self) -> *const OpaquePtr { + self.ptr + } + + pub fn context<'a>(&self) -> &'a ExecutingContext { + assert!(!self.context.is_null(), "Context PTR must not be null"); + unsafe { &*self.context } + } + + <% } %> + + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = generateValidRustIdentifier(_.snakeCase(prop.name)); %> + <% if (isVoidType(prop.type)) { %> + pub fn <%= propName %>(&self) { + unsafe { + ((*self.method_pointer).<%= propName %>)(self(.ptr())); + }; + } + <% } else { %> + pub fn <%= propName %>(&self) -> <%= generateMethodReturnType(prop.type) %> { + let value = unsafe { + ((*self.method_pointer).<%= propName %>)(self.ptr()) + }; + <%= generatePropReturnStatements(prop.type) %> + } + <% } %> + + <% if (!prop.readonly) { %> + pub fn set_<%= _.snakeCase(prop.name) %>(&self, value: <%= generateMethodReturnType(prop.type) %>, exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).set_<%= _.snakeCase(prop.name) %>)(self.ptr(), <%= generateMethodParametersName([{name: 'value', type: prop.type}]) %>exception_state.ptr) + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = generateValidRustIdentifier(_.snakeCase(method.name)); %> + <% if (isVoidType(method.returnType)) { %> + pub fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<(), String> { + unsafe { + ((*self.method_pointer).<%= methodName %>)(self.ptr(), <%= generateMethodParametersName(method.args) %>exception_state.ptr); + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + Ok(()) + } + <% } else { %> + pub fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<<%= generateMethodReturnType(method.returnType) %>, String> { + let value = unsafe { + ((*self.method_pointer).<%= methodName %>)(self.ptr(), <%= generateMethodParametersName(method.args) %>exception_state.ptr) + }; + if exception_state.has_exception() { + return Err(exception_state.stringify(self.context())); + } + <%= generateMethodReturnStatements(method.returnType) %> + } + <% } %> + <% }); %> +} + +<% if (!object.parent) { %> +impl Drop for <%= className %> { + fn drop(&mut self) { + unsafe { + ((*self.method_pointer).release)(self.ptr()); + } + } +} +<% } %> + +<% var parentMethodsSuperTrait = object.parent ? `: ${object.parent}Methods` : ''; %> +pub trait <%= className %>Methods<%= parentMethodsSuperTrait %> { + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = generateValidRustIdentifier(_.snakeCase(prop.name)); %> + <% if (isVoidType(prop.type)) { %> + fn <%= propName %>(&self); + <% } else { %> + fn <%= propName %>(&self) -> <%= generateMethodReturnType(prop.type) %>; + <% } %> + + <% if (!prop.readonly) { %> + fn set_<%= _.snakeCase(prop.name) %>(&self, value: <%= generateMethodReturnType(prop.type) %>, exception_state: &ExceptionState) -> Result<(), String>; + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = generateValidRustIdentifier(_.snakeCase(method.name)); %> + <% if (isVoidType(method.returnType)) { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<(), String>; + <% } else { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<<%= generateMethodReturnType(method.returnType) %>, String>; + <% } %> + <% }); %> + fn as_<%= _.snakeCase(className) %>(&self) -> &<%= className %>; +} + +impl <%= className %>Methods for <%= className %> { + <% _.forEach(object.props, function(prop, index) { %> + <% var propName = generateValidRustIdentifier(_.snakeCase(prop.name)); %> + <% if (isVoidType(prop.type)) { %> + fn <%= propName %>(&self) { + self.<%= propName %>() + } + <% } else { %> + fn <%= propName %>(&self) -> <%= generateMethodReturnType(prop.type) %> { + self.<%= propName %>() + } + <% } %> + + <% if (!prop.readonly) { %> + fn set_<%= _.snakeCase(prop.name) %>(&self, value: <%= generateMethodReturnType(prop.type) %>, exception_state: &ExceptionState) -> Result<(), String> { + self.set_<%= _.snakeCase(prop.name) %>(value, exception_state) + } + <% } %> + <% }); %> + + <% _.forEach(object.methods, function(method, index) { %> + <% var methodName = generateValidRustIdentifier(_.snakeCase(method.name)); %> + <% if (isVoidType(method.returnType)) { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<(), String> { + self.<%= methodName %>(<%= generateParentMethodParametersName(method.args) %>exception_state) + } + <% } else { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<<%= generateMethodReturnType(method.returnType) %>, String> { + self.<%= methodName %>(<%= generateParentMethodParametersName(method.args) %>exception_state) + } + <% } %> + <% }); %> + fn as_<%= _.snakeCase(className) %>(&self) -> &<%= className %> { + self + } +} + +<% var parentKey = ''; %> +<% _.forEach(inheritedObjects, function (parentObject) { %> + <% parentKey = parentKey === '' ? _.snakeCase(parentObject.name) : `${parentKey}.${_.snakeCase(parentObject.name)}`; %> +impl <%= parentObject.name %>Methods for <%= className %> { + <% _.forEach(parentObject.props, function(prop, index) { %> + <% var propName = generateValidRustIdentifier(_.snakeCase(prop.name)); %> + <% if (isVoidType(prop.type)) { %> + fn <%= propName %>(&self) { + self.<%= parentKey %>.<%= propName %>() + } + <% } else { %> + fn <%= propName %>(&self) -> <%= generateMethodReturnType(prop.type) %> { + self.<%= parentKey %>.<%= propName %>() + } + <% } %> + + <% if (!prop.readonly) { %> + fn set_<%= _.snakeCase(prop.name) %>(&self, value: <%= generateMethodReturnType(prop.type) %>, exception_state: &ExceptionState) -> Result<(), String> { + self.<%= parentKey %>.set_<%= _.snakeCase(prop.name) %>(value, exception_state) + } + <% } %> + <% }); %> + + <% _.forEach(parentObject.methods, function(method, index) { %> + <% var methodName = generateValidRustIdentifier(_.snakeCase(method.name)); %> + <% if (isVoidType(method.returnType)) { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<(), String> { + self.<%= parentKey %>.<%= methodName %>(<%= generateParentMethodParametersName(method.args) %>exception_state) + } + <% } else { %> + fn <%= methodName %>(&self, <%= generateMethodParametersTypeWithName(method.args) %>exception_state: &ExceptionState) -> Result<<%= generateMethodReturnType(method.returnType) %>, String> { + self.<%= parentKey %>.<%= methodName %>(<%= generateParentMethodParametersName(method.args) %>exception_state) + } + <% } %> + <% }); %> + fn as_<%= _.snakeCase(parentObject.name) %>(&self) -> &<%= parentObject.name %> { + &self.<%= parentKey %> + } +} +<% }); %> diff --git a/bridge/scripts/code_generator/templates/json_templates/element_type_helper.h.tpl b/bridge/scripts/code_generator/templates/json_templates/element_type_helper.h.tpl index a5e248765c..afedcb2609 100644 --- a/bridge/scripts/code_generator/templates/json_templates/element_type_helper.h.tpl +++ b/bridge/scripts/code_generator/templates/json_templates/element_type_helper.h.tpl @@ -44,6 +44,10 @@ struct DowncastTraits { static bool AllowFrom(const Node& node) { return node.IsHTMLElement() && IsA(To(node)); } + static bool AllowFrom(const EventTarget& event_target) { + return event_target.IsNode() && To(event_target).IsHTMLElement() && + To(event_target).tagName() == html_names::k${ name }; + } }; `; } %> diff --git a/bridge/test/test.cmake b/bridge/test/test.cmake index e2fb3d45d6..d9904d7a00 100644 --- a/bridge/test/test.cmake +++ b/bridge/test/test.cmake @@ -54,7 +54,6 @@ target_compile_definitions(webf_unit_test PUBLIC -DFLUTTER_BACKEND=0) target_compile_definitions(webf_unit_test PUBLIC -DSPEC_FILE_PATH="${CMAKE_CURRENT_SOURCE_DIR}") target_compile_definitions(webf_unit_test PUBLIC -DUNIT_TEST=1) -target_compile_definitions(webf_static PUBLIC -DFLUTTER_BACKEND=1) if (DEFINED ENV{LIBRARY_OUTPUT_DIR}) set_target_properties(webf_unit_test PROPERTIES diff --git a/bridge/test/webf_test_env.cc b/bridge/test/webf_test_env.cc index 8932dddc2c..ef8c57baa7 100644 --- a/bridge/test/webf_test_env.cc +++ b/bridge/test/webf_test_env.cc @@ -179,6 +179,12 @@ void TEST_flushUICommand(double contextId) { void TEST_CreateBindingObject(double context_id, void* native_binding_object, int32_t type, void* args, int32_t argc) {} +void TEST_LoadNativeLibrary(double context_id, + SharedNativeString* lib_name, + void* initialize_data, + void* import_data, + LoadNativeLibraryCallback callback) {} + void TEST_GetWidgetElementShape() {} void TEST_onJsLog(double contextId, int32_t level, const char*) {} @@ -329,8 +335,10 @@ std::vector TEST_getMockDartMethods(OnJSError onJSError) { reinterpret_cast(TEST_toBlob), reinterpret_cast(TEST_flushUICommand), reinterpret_cast(TEST_CreateBindingObject), + reinterpret_cast(TEST_LoadNativeLibrary), reinterpret_cast(TEST_GetWidgetElementShape)}; + WEBF_LOG(VERBOSE) << " ON JS ERROR" << onJSError; mockMethods.emplace_back(reinterpret_cast(onJSError)); mockMethods.emplace_back(reinterpret_cast(TEST_onJsLog)); return mockMethods; diff --git a/bridge/third_party/quickjs/compat/win32/pthread-win32 b/bridge/third_party/quickjs/compat/win32/pthread-win32 new file mode 160000 index 0000000000..3309f4d6e7 --- /dev/null +++ b/bridge/third_party/quickjs/compat/win32/pthread-win32 @@ -0,0 +1 @@ +Subproject commit 3309f4d6e7538f349ae450347b02132ecb0606a7 diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/ANNOUNCE b/bridge/third_party/quickjs/compat/win32/pthreads/ANNOUNCE deleted file mode 100644 index 950c86ff03..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/ANNOUNCE +++ /dev/null @@ -1,483 +0,0 @@ -PTHREADS-WIN32 RELEASE 2.9.0 (2012-05-25) ------------------------------------------ -Web Site: http://sourceware.org/pthreads-win32/ -FTP Site: ftp://sourceware.org/pub/pthreads-win32 -Maintainer: Ross Johnson - - -We are pleased to announce the availability of a new release of -Pthreads-win32, an Open Source Software implementation of the -Threads component of the POSIX 1003.1 2001 Standard for Microsoft's -Win32 environment. Some functions from other sections of POSIX -1003.1 2001 are also supported including semaphores and scheduling -functions. - -Some common non-portable functions are also implemented for -additional compatibility, as are a few functions specific -to pthreads-win32 for easier integration with Win32 applications. - -Pthreads-win32 is free software, distributed under the GNU Lesser -General Public License (LGPL). - - -Acknowledgements ----------------- -This library is based originally on a Win32 pthreads -implementation contributed by John Bossom. - -The implementation of Condition Variables uses algorithms developed -by Alexander Terekhov and Louis Thomas. - -The implementation of POSIX mutexes has been improved by Thomas Pfaff -and later by Alexander Terekhov. - -The implementation of Spinlocks and Barriers was contributed -by Ross Johnson. - -The implementation of read/write locks was contributed by -Aurelio Medina and improved by Alexander Terekhov. - -Many others have contributed significant time and effort to solve crutial -problems in order to make the library workable, robust and reliable. - -Thanks to Xavier Leroy for granting permission to use and modify his -LinuxThreads manual pages. - -Thanks to The Open Group for making the Single Unix Specification -publicly available - many of the manual pages included in the package -were extracted from it. - -There is also a separate CONTRIBUTORS file. This file and others are -on the web site: - - http://sourceware.org/pthreads-win32 - -As much as possible, the ChangeLog file acknowledges contributions to the -code base in more detail. - - -Changes since the last release ------------------------------- -These are now documented in the NEWS file. -See the ChangeLog file also. - - -Known Bugs ----------- -These are now documented in the BUGS file. - - -Level of standards conformance ------------------------------- - -The following POSIX 1003.1 2001 options are defined and set to 200112L: - - _POSIX_THREADS - _POSIX_THREAD_SAFE_FUNCTIONS - _POSIX_THREAD_ATTR_STACKSIZE - _POSIX_THREAD_PRIORITY_SCHEDULING - _POSIX_SEMAPHORES - _POSIX_READER_WRITER_LOCKS - _POSIX_SPIN_LOCKS - _POSIX_BARRIERS - - -The following POSIX 1003.1 2001 options are defined and set to -1: - - _POSIX_THREAD_ATTR_STACKADDR - _POSIX_THREAD_PRIO_INHERIT - _POSIX_THREAD_PRIO_PROTECT - _POSIX_THREAD_PROCESS_SHARED - - -The following POSIX 1003.1 2001 limits are defined and set: - - _POSIX_THREAD_THREADS_MAX - _POSIX_SEM_VALUE_MAX - _POSIX_SEM_NSEMS_MAX - _POSIX_THREAD_KEYS_MAX - _POSIX_THREAD_DESTRUCTOR_ITERATIONS - PTHREAD_STACK_MIN - PTHREAD_THREADS_MAX - SEM_VALUE_MAX - SEM_NSEMS_MAX - PTHREAD_KEYS_MAX - PTHREAD_DESTRUCTOR_ITERATIONS - - -The following functions are implemented: - - --------------------------- - PThreads - --------------------------- - pthread_attr_init - pthread_attr_destroy - pthread_attr_getdetachstate - pthread_attr_getstackaddr - pthread_attr_getstacksize - pthread_attr_setdetachstate - pthread_attr_setstackaddr - pthread_attr_setstacksize - - pthread_create - pthread_detach - pthread_equal - pthread_exit - pthread_join - pthread_once - pthread_self - - pthread_cancel - pthread_cleanup_pop - pthread_cleanup_push - pthread_setcancelstate - pthread_setcanceltype - pthread_testcancel - - --------------------------- - Thread Specific Data - --------------------------- - pthread_key_create - pthread_key_delete - pthread_setspecific - pthread_getspecific - - --------------------------- - Mutexes - --------------------------- - pthread_mutexattr_init - pthread_mutexattr_destroy - pthread_mutexattr_getpshared - pthread_mutexattr_setpshared - pthread_mutexattr_gettype - pthread_mutexattr_settype (types: PTHREAD_MUTEX_DEFAULT - PTHREAD_MUTEX_NORMAL - PTHREAD_MUTEX_ERRORCHECK - PTHREAD_MUTEX_RECURSIVE ) - pthread_mutexattr_getrobust - pthread_mutexattr_setrobust (values: PTHREAD_MUTEX_STALLED - PTHREAD_MUTEX_ROBUST) - pthread_mutex_init - pthread_mutex_destroy - pthread_mutex_lock - pthread_mutex_trylock - pthread_mutex_timedlock - pthread_mutex_unlock - pthread_mutex_consistent - - --------------------------- - Condition Variables - --------------------------- - pthread_condattr_init - pthread_condattr_destroy - pthread_condattr_getpshared - pthread_condattr_setpshared - - pthread_cond_init - pthread_cond_destroy - pthread_cond_wait - pthread_cond_timedwait - pthread_cond_signal - pthread_cond_broadcast - - --------------------------- - Read/Write Locks - --------------------------- - pthread_rwlock_init - pthread_rwlock_destroy - pthread_rwlock_tryrdlock - pthread_rwlock_trywrlock - pthread_rwlock_rdlock - pthread_rwlock_timedrdlock - pthread_rwlock_rwlock - pthread_rwlock_timedwrlock - pthread_rwlock_unlock - pthread_rwlockattr_init - pthread_rwlockattr_destroy - pthread_rwlockattr_getpshared - pthread_rwlockattr_setpshared - - --------------------------- - Spin Locks - --------------------------- - pthread_spin_init - pthread_spin_destroy - pthread_spin_lock - pthread_spin_unlock - pthread_spin_trylock - - --------------------------- - Barriers - --------------------------- - pthread_barrier_init - pthread_barrier_destroy - pthread_barrier_wait - pthread_barrierattr_init - pthread_barrierattr_destroy - pthread_barrierattr_getpshared - pthread_barrierattr_setpshared - - --------------------------- - Semaphores - --------------------------- - sem_init - sem_destroy - sem_post - sem_wait - sem_trywait - sem_timedwait - sem_getvalue (# free if +ve, # of waiters if -ve) - sem_open (returns an error ENOSYS) - sem_close (returns an error ENOSYS) - sem_unlink (returns an error ENOSYS) - - --------------------------- - RealTime Scheduling - --------------------------- - pthread_attr_getschedparam - pthread_attr_setschedparam - pthread_attr_getinheritsched - pthread_attr_setinheritsched - pthread_attr_getschedpolicy (only supports SCHED_OTHER) - pthread_attr_setschedpolicy (only supports SCHED_OTHER) - pthread_getschedparam - pthread_setschedparam - pthread_getconcurrency - pthread_setconcurrency - pthread_attr_getscope - pthread_attr_setscope (only supports PTHREAD_SCOPE_SYSTEM) - sched_get_priority_max - sched_get_priority_min - sched_rr_get_interval (returns an error ENOTSUP) - sched_setscheduler (only supports SCHED_OTHER) - sched_getscheduler (only supports SCHED_OTHER) - sched_yield - - --------------------------- - Signals - --------------------------- - pthread_sigmask - pthread_kill (only supports zero sig value, - for thread validity checking) - - --------------------------- - Non-portable routines (see the README.NONPORTABLE file for usage) - --------------------------- - pthread_getw32threadhandle_np - pthread_timechange_handler_np - pthread_delay_np - pthread_getunique_np - pthread_mutexattr_getkind_np - pthread_mutexattr_setkind_np (types: PTHREAD_MUTEX_FAST_NP, - PTHREAD_MUTEX_ERRORCHECK_NP, - PTHREAD_MUTEX_RECURSIVE_NP, - PTHREAD_MUTEX_ADAPTIVE_NP, - PTHREAD_MUTEX_TIMED_NP) - pthread_num_processors_np - (The following four routines may be required when linking statically. - The process_* routines should not be needed for MSVC or GCC.) - pthread_win32_process_attach_np - pthread_win32_process_detach_np - (The following routines should only be needed to manage implicit - POSIX handles i.e. when Win native threads call POSIX thread routines - (other than pthread_create)) - pthread_win32_thread_attach_np - pthread_win32_thread_detach_np - - --------------------------- - Static Initializers - --------------------------- - PTHREAD_ONCE_INIT - PTHREAD_MUTEX_INITIALIZER - PTHREAD_RECURSIVE_MUTEX_INITIALIZER - PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP - PTHREAD_ERRORCHECK_MUTEX_INITIALIZER - PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP - PTHREAD_COND_INITIALIZER - PTHREAD_RWLOCK_INITIALIZER - PTHREAD_SPINLOCK_INITIALIZER - - -The library includes two non-API functions for creating cancellation -points in applications and libraries: - - pthreadCancelableWait - pthreadCancelableTimedWait - - -The following functions are not implemented: - - --------------------------- - RealTime Scheduling - --------------------------- - pthread_mutex_getprioceiling - pthread_mutex_setprioceiling - pthread_mutex_attr_getprioceiling - pthread_mutex_attr_getprotocol - pthread_mutex_attr_setprioceiling - pthread_mutex_attr_setprotocol - - --------------------------- - Fork Handlers - --------------------------- - pthread_atfork - - --------------------------- - Stdio - --------------------------- - flockfile - ftrylockfile - funlockfile - getc_unlocked - getchar_unlocked - putc_unlocked - putchar_unlocked - - --------------------------- - Thread-Safe C Runtime Library - --------------------------- - readdir_r - getgrgid_r - getgrnam_r - getpwuid_r - getpwnam_r - - --------------------------- - Signals - --------------------------- - sigtimedwait - sigwait - sigwaitinfo - - --------------------------- - General - --------------------------- - sysconf - - --------------------------- - Thread-Safe C Runtime Library (macros) - --------------------------- - strtok_r - asctime_r - ctime_r - gmtime_r - localtime_r - rand_r - - -Availability ------------- - -The prebuilt DLL, export libs (for both MSVC and Mingw32), and the header -files (pthread.h, semaphore.h, sched.h) are available along with the -complete source code. - -The source code can be found at: - - ftp://sources.redhat.com/pub/pthreads-win32 - -and as individual source code files at - - ftp://sources.redhat.com/pub/pthreads-win32/source - -The pre-built DLL, export libraries and include files can be found at: - - ftp://sources.redhat.com/pub/pthreads-win32/dll-latest - - - -Mailing List ------------- - -There is a mailing list for discussing pthreads on Win32. To join, -send email to: - - pthreads-win32-subscribe@sourceware.cygnus.com - - -Application Development Environments ------------------------------------- - -See the README file for more information. - -MSVC: -MSVC using SEH works. Distribute pthreadVSE.dll with your application. -MSVC using C++ EH works. Distribute pthreadVCE.dll with your application. -MSVC using C setjmp/longjmp works. Distribute pthreadVC.dll with your application. - - -Mingw32: -See the FAQ, Questions 6 and 10. - -Mingw using C++ EH works. Distribute pthreadGCE.dll with your application. -Mingw using C setjmp/longjmp works. Distribute pthreadGC.dll with your application. - - -Cygwin: (http://sourceware.cygnus.com/cygwin/) -Developers using Cygwin do not need pthreads-win32 since it has POSIX threads -support. Refer to its documentation for details and extent. - - -UWIN: -UWIN is a complete Unix-like environment for Windows from AT&T. Pthreads-win32 -doesn't currently support UWIN (and vice versa), but that may change in the -future. - -Generally: -For convenience, the following pre-built files are available on the FTP site -(see Availability above): - - pthread.h - for POSIX threads - semaphore.h - for POSIX semaphores - sched.h - for POSIX scheduling - pthreadVCE.dll - built with MSVC++ compiler using C++ EH - pthreadVCE.lib - pthreadVC.dll - built with MSVC compiler using C setjmp/longjmp - pthreadVC.lib - pthreadVSE.dll - built with MSVC compiler using SEH - pthreadVSE.lib - pthreadGCE.dll - built with Mingw32 G++ 2.95.2-1 - pthreadGC.dll - built with Mingw32 GCC 2.95.2-1 using setjmp/longjmp - libpthreadGCE.a - derived from pthreadGCE.dll - libpthreadGC.a - derived from pthreadGC.dll - gcc.dll - needed if distributing applications that use - pthreadGCE.dll (but see the FAQ Q 10 for the latest - related information) - -These are the only files you need in order to build POSIX threads -applications for Win32 using either MSVC or Mingw32. - -See the FAQ file in the source tree for additional information. - - -Documentation -------------- - -For the authoritative reference, see the online POSIX -standard reference at: - - http://www.OpenGroup.org - -For POSIX Thread API programming, several reference books are -available: - - Programming with POSIX Threads - David R. Butenhof - Addison-Wesley (pub) - - Pthreads Programming - By Bradford Nichols, Dick Buttlar & Jacqueline Proulx Farrell - O'Reilly (pub) - -On the web: see the links at the bottom of the pthreads-win32 site: - - http://sources.redhat.com/pthreads-win32/ - - Currently, there is no documentation included in the package apart - from the copious comments in the source code. - - - -Enjoy! - -Ross Johnson diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/BUGS b/bridge/third_party/quickjs/compat/win32/pthreads/BUGS deleted file mode 100644 index 285ba4eb98..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/BUGS +++ /dev/null @@ -1,141 +0,0 @@ ----------- -Known bugs ----------- - -1. Not strictly a bug, more of a gotcha. - - Under MS VC++ (only tested with version 6.0), a term_func - set via the standard C++ set_terminate() function causes the - application to abort. - - Notes from the MSVC++ manual: - 1) A term_func() should call exit(), otherwise - abort() will be called on return to the caller. - A call to abort() raises SIGABRT and the default signal handler - for all signals terminates the calling program with - exit code 3. - 2) A term_func() must not throw an exception. Therefore - term_func() should not call pthread_exit(), which - works by throwing an exception (pthreadVCE or pthreadVSE) - or by calling longjmp (pthreadVC). - - Workaround: avoid using pthread_exit() in C++ applications. Exit - threads by dropping through the end of the thread routine. - -2. Cancellation problems in C++ builds - - Milan Gardian - - [Note: It's not clear if this problem isn't simply due to the context - switch in pthread_cancel() which occurs unless the QueueUserAPCEx - library and driver are installed and used. Just like setjmp/longjmp, - this is probably not going to work well in C++. In any case, unless for - some very unusual reason you really must use the C++ build then please - use the C build pthreadVC2.dll or pthreadGC2.dll, i.e. for C++ - applications.] - - This is suspected to be a compiler bug in VC6.0, and also seen in - VC7.0 and VS .NET 2003. The GNU C++ compiler does not have a problem - with this, and it has been reported that the Intel C++ 8.1 compiler - and Visual C++ 2005 Express Edition Beta2 pass tests\semaphore4.c - (which exposes the bug). - - Workaround [rpj - 2 Feb 2002] - ----------------------------- - [Please note: this workaround did not solve a similar problem in - snapshot-2004-11-03 or later, even though similar symptoms were seen. - tests\semaphore4.c fails in that snapshot for the VCE version of the - DLL.] - - The problem disappears when /Ob0 is used, i.e. /O2 /Ob0 works OK, - but if you want to use inlining optimisation you can be much more - specific about where it's switched off and on by using a pragma. - - So the inlining optimisation is interfering with the way that cleanup - handlers are run. It appears to relate to auto-inlining of class methods - since this is the only auto inlining that is performed at /O1 optimisation - (functions with the "inline" qualifier are also inlined, but the problem - doesn't appear to involve any such functions in the library or testsuite). - - In order to confirm the inlining culprit, the following use of pragmas - eliminate the problem but I don't know how to make it transparent, putting - it in, say, pthread.h where pthread_cleanup_push defined as a macro. - - #pragma inline_depth(0) - pthread_cleanup_push(handlerFunc, (void *) &arg); - - /* ... */ - - pthread_cleanup_pop(0); - #pragma inline_depth() - - Note the empty () pragma value after the pop macro. This resets depth to the - default. Or you can specify a non-zero depth here. - - The pragma is also needed (and now used) within the library itself wherever - cleanup handlers are used (condvar.c and rwlock.c). - - Use of these pragmas allows compiler optimisations /O1 and /O2 to be - used for either or both the library and applications. - - Experimenting further, I found that wrapping the actual cleanup handler - function with #pragma auto_inline(off|on) does NOT work. - - MSVC6.0 doesn't appear to support the C99 standard's _Pragma directive, - however, later versions may. This form is embeddable inside #define - macros, which would be ideal because it would mean that it could be added - to the push/pop macro definitions in pthread.h and hidden from the - application programmer. - - [/rpj] - - Original problem description - ---------------------------- - - The cancellation (actually, cleanup-after-cancel) tests fail when using VC - (professional) optimisation switches (/O1 or /O2) in pthreads library. I - have not investigated which concrete optimisation technique causes this - problem (/Og, /Oi, /Ot, /Oy, /Ob1, /Gs, /Gf, /Gy, etc.), but here is a - summary of builds and corresponding failures: - - * pthreads VSE (optimised tests): OK - * pthreads VCE (optimised tests): Failed "cleanup1" test (runtime) - - * pthreads VSE (DLL in CRT, optimised tests): OK - * pthreads VCE (DLL in CRT, optimised tests): Failed "cleanup1" test - (runtime) - - Please note that while in VSE version of the pthreads library the - optimisation does not really have any impact on the tests (they pass OK), in - VCE version addition of optimisation (/O2 in this case) causes the tests to - fail uniformly - either in "cleanup0" or "cleanup1" test cases. - - Please note that all the tests above use default pthreads DLL (no - optimisations, linked with either static or DLL CRT, based on test type). - Therefore the problem lies not within the pthreads DLL but within the - compiled client code (the application using pthreads -> involvement of - "pthread.h"). - - I think the message of this section is that usage of VCE version of pthreads - in applications relying on cancellation/cleanup AND using optimisations for - creation of production code is highly unreliable for the current version of - the pthreads library. - -3. The Borland Builder 5.5 version of the library produces memory read exceptions -in some tests. - -4. pthread_barrier_wait() can deadlock if the number of potential calling -threads for a particular barrier is greater than the barrier count parameter -given to pthread_barrier_init() for that barrier. - -This is due to the very lightweight implementation of pthread-win32 barriers. -To cope with more than "count" possible waiters, barriers must effectively -implement all the same safeguards as condition variables, making them much -"heavier" than at present. - -The workaround is to ensure that no more than "count" threads attempt to wait -at the barrier. - -5. Canceling a thread blocked on pthread_once appears not to work in the MSVC++ -version of the library "pthreadVCE.dll". The test case "once3.c" hangs. I have no -clues on this at present. All other versions pass this test ok - pthreadsVC.dll, -pthreadsVSE.dll, pthreadsGC.dll and pthreadsGCE.dll. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/CONTRIBUTORS b/bridge/third_party/quickjs/compat/win32/pthreads/CONTRIBUTORS deleted file mode 100644 index da31ff266c..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/CONTRIBUTORS +++ /dev/null @@ -1,140 +0,0 @@ -Contributors (in approximate order of appearance) - -[See also the ChangeLog file where individuals are -attributed in log entries. Likewise in the FAQ file.] - -Ben Elliston bje at cygnus dot com - Initiated the project; - setup the project infrastructure (CVS, web page, etc.); - early prototype routines. -Ross Johnson Ross dot Johnson at dot homemail dot com dot au - early prototype routines; - ongoing project coordination/maintenance; - implementation of spin locks and barriers; - various enhancements; - bug fixes; - documentation; - testsuite. -Robert Colquhoun rjc at trump dot net dot au - Early bug fixes. -John E. Bossom John dot Bossom at cognos dot com - Contributed substantial original working implementation; - bug fixes; - ongoing guidance and standards interpretation. -Anders Norlander anorland at hem2 dot passagen dot se - Early enhancements and runtime checking for supported - Win32 routines. -Tor Lillqvist tml at iki dot fi - General enhancements; - early bug fixes to condition variables. -Scott Lightner scott at curriculum dot com - Bug fix. -Kevin Ruland Kevin dot Ruland at anheuser-busch dot com - Various bug fixes. -Mike Russo miker at eai dot com - Bug fix. -Mark E. Armstrong avail at pacbell dot net - Bug fixes. -Lorin Hochstein lmh at xiphos dot ca - general bug fixes; bug fixes to condition variables. -Peter Slacik Peter dot Slacik at tatramed dot sk - Bug fixes. -Mumit Khan khan at xraylith dot wisc dot edu - Fixes to work with Mingw32. -Milan Gardian mg at tatramed dot sk - Bug fixes and reports/analyses of obscure problems. -Aurelio Medina aureliom at crt dot com - First implementation of read-write locks. -Graham Dumpleton Graham dot Dumpleton at ra dot pad dot otc dot telstra dot com dot au - Bug fix in condition variables. -Tristan Savatier tristan at mpegtv dot com - WinCE port. -Erik Hensema erik at hensema dot xs4all dot nl - Bug fixes. -Rich Peters rpeters at micro-magic dot com -Todd Owen towen at lucidcalm dot dropbear dot id dot au - Bug fixes to dll loading. -Jason Nye jnye at nbnet dot nb dot ca - Implementation of async cancelation. -Fred Forester fforest at eticomm dot net -Kevin D. Clark kclark at cabletron dot com -David Baggett dmb at itasoftware dot com - Bug fixes. -Paul Redondo paul at matchvision dot com -Scott McCaskill scott at 3dfx dot com - Bug fixes. -Jef Gearhart jgearhart at tpssys dot com - Bug fix. -Arthur Kantor akantor at bexusa dot com - Mutex enhancements. -Steven Reddie smr at essemer dot com dot au - Bug fix. -Alexander Terekhov TEREKHOV at de dot ibm dot com - Re-implemented and improved read-write locks; - (with Louis Thomas) re-implemented and improved - condition variables; - enhancements to semaphores; - enhancements to mutexes; - new mutex implementation in 'futex' style; - suggested a robust implementation of pthread_once - similar to that implemented by V.Kliathcko; - system clock change handling re CV timeouts; - bug fixes. -Thomas Pfaff tpfaff at gmx dot net - Changes to make C version usable with C++ applications; - re-implemented mutex routines to avoid Win32 mutexes - and TryEnterCriticalSection; - procedure to fix Mingw32 thread-safety issues. -Franco Bez franco dot bez at gmx dot de - procedure to fix Mingw32 thread-safety issues. -Louis Thomas lthomas at arbitrade dot com - (with Alexander Terekhov) re-implemented and improved - condition variables. -David Korn dgk at research dot att dot com - Ported to UWIN. -Phil Frisbie, Jr. phil at hawksoft dot com - Bug fix. -Ralf Brese Ralf dot Brese at pdb4 dot siemens dot de - Bug fix. -prionx at juno dot com prionx at juno dot com - Bug fixes. -Max Woodbury mtew at cds dot duke dot edu - POSIX versioning conditionals; - reduced namespace pollution; - idea to separate routines to reduce statically - linked image sizes. -Rob Fanner rfanner at stonethree dot com - Bug fix. -Michael Johnson michaelj at maine dot rr dot com - Bug fix. -Nicolas Barry boozai at yahoo dot com - Bug fixes. -Piet van Bruggen pietvb at newbridges dot nl - Bug fix. -Makoto Kato raven at oldskool dot jp - AMD64 port. -Panagiotis E. Hadjidoukas peh at hpclab dot ceid dot upatras dot gr - phadjido at cs dot uoi dot gr - Contributed the QueueUserAPCEx package which - makes preemptive async cancelation possible. -Will Bryant will dot bryant at ecosm dot com - Borland compiler patch and makefile. -Anuj Goyal anuj dot goyal at gmail dot com - Port to Digital Mars compiler. -Gottlob Frege gottlobfrege at gmail dot com - re-implemented pthread_once (version 2) - (pthread_once cancellation added by rpj). -Vladimir Kliatchko vladimir at kliatchko dot com - reimplemented pthread_once with the same form - as described by A.Terekhov (later version 2); - implementation of MCS (Mellor-Crummey/Scott) locks. -Ramiro Polla ramiro.polla at gmail dot com - static library auto init/cleanup on application - start/exit via RT hooks (MSC and GCC compilers only). -Daniel Richard G. skunk at iSKUNK dot org - Patches and cleanups for x86 and x64, particularly - across a range of MS build environments. -John Kamp john dot kamp at globalgraphics dot com - Patches to fix various problems on x64; brutal testing - particularly using high memory run environments. - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/COPYING b/bridge/third_party/quickjs/compat/win32/pthreads/COPYING deleted file mode 100644 index 5cfea0d0ed..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/COPYING +++ /dev/null @@ -1,150 +0,0 @@ - pthreads-win32 - a POSIX threads library for Microsoft Windows - - -This file is Copyrighted ------------------------- - - This file is covered under the following Copyright: - - Copyright (C) 2001,2006 Ross P. Johnson - All rights reserved. - - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -Pthreads-win32 is covered by the GNU Lesser General Public License ------------------------------------------------------------------- - - Pthreads-win32 is open software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public License - as published by the Free Software Foundation version 2.1 of the - License. - - Pthreads-win32 is several binary link libraries, several modules, - associated interface definition files and scripts used to control - its compilation and installation. - - Pthreads-win32 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - A copy of the GNU Lesser General Public License is distributed with - pthreads-win32 under the filename: - - COPYING.LIB - - You should have received a copy of the version 2.1 GNU Lesser General - Public License with pthreads-win32; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307 - USA - - The contact addresses for pthreads-win32 is as follows: - - Web: http://sources.redhat.com/pthreads-win32 - Email: Ross Johnson - Please use: Firstname.Lastname@homemail.com.au - - - -Pthreads-win32 copyrights and exception files ---------------------------------------------- - - With the exception of the files listed below, Pthreads-win32 - is covered under the following GNU Lesser General Public License - Copyrights: - - Pthreads-win32 - POSIX Threads Library for Win32 - Copyright(C) 1998 John E. Bossom - Copyright(C) 1999,2006 Pthreads-win32 contributors - - The current list of contributors is contained - in the file CONTRIBUTORS included with the source - code distribution. The current list of CONTRIBUTORS - can also be seen at the following WWW location: - http://sources.redhat.com/pthreads-win32/contributors.html - - Contact Email: Ross Johnson - Please use: Firstname.Lastname@homemail.com.au - - These files are not covered under one of the Copyrights listed above: - - COPYING - COPYING.LIB - tests/rwlock7.c - - This file, COPYING, is distributed under the Copyright found at the - top of this file. It is important to note that you may distribute - verbatim copies of this file but you may not modify this file. - - The file COPYING.LIB, which contains a copy of the version 2.1 - GNU Lesser General Public License, is itself copyrighted by the - Free Software Foundation, Inc. Please note that the Free Software - Foundation, Inc. does NOT have a copyright over Pthreads-win32, - only the COPYING.LIB that is supplied with pthreads-win32. - - The file tests/rwlock7.c is derived from code written by - Dave Butenhof for his book 'Programming With POSIX(R) Threads'. - The original code was obtained by free download from his website - http://home.earthlink.net/~anneart/family/Threads/source.html - and did not contain a copyright or author notice. It is assumed to - be freely distributable. - - In all cases one may use and distribute these exception files freely. - And because one may freely distribute the LGPL covered files, the - entire pthreads-win32 source may be freely used and distributed. - - - -General Copyleft and License info ---------------------------------- - - For general information on Copylefts, see: - - http://www.gnu.org/copyleft/ - - For information on GNU Lesser General Public Licenses, see: - - http://www.gnu.org/copyleft/lesser.html - http://www.gnu.org/copyleft/lesser.txt - - -Why pthreads-win32 did not use the GNU General Public License -------------------------------------------------------------- - - The goal of the pthreads-win32 project has been to - provide a quality and complete implementation of the POSIX - threads API for Microsoft Windows within the limits imposed - by virtue of it being a stand-alone library and not - linked directly to other POSIX compliant libraries. For - example, some functions and features, such as those based - on POSIX signals, are missing. - - Pthreads-win32 is a library, available in several different - versions depending on supported compilers, and may be used - as a dynamically linked module or a statically linked set of - binary modules. It is not an application on it's own. - - It was fully intended that pthreads-win32 be usable with - commercial software not covered by either the GPL or the LGPL - licenses. Pthreads-win32 has many contributors to it's - code base, many of whom have done so because they have - used the library in commercial or proprietry software - projects. - - Releasing pthreads-win32 under the LGPL ensures that the - library can be used widely, while at the same time ensures - that bug fixes and improvements to the pthreads-win32 code - itself is returned to benefit all current and future users - of the library. - - Although pthreads-win32 makes it possible for applications - that use POSIX threads to be ported to Win32 platforms, the - broader goal of the project is to encourage the use of open - standards, and in particular, to make it just a little easier - for developers writing Win32 applications to consider - widening the potential market for their products. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/COPYING.LIB b/bridge/third_party/quickjs/compat/win32/pthreads/COPYING.LIB deleted file mode 100644 index b1e3f5a263..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/COPYING.LIB +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/ChangeLog b/bridge/third_party/quickjs/compat/win32/pthreads/ChangeLog deleted file mode 100644 index 42abcc457a..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/ChangeLog +++ /dev/null @@ -1,5211 +0,0 @@ -2012-03-18 Ross Johnson - - * create.c (pthread_create): add __cdecl attribute to thread routine - arg - * implement.h (pthread_key_t): add __cdecl attribute to destructor - element - (ThreadParms): likewise for start element - * pthread.h (pthread_create): add __cdecl to prototype start arg - (pthread_once): likewise for init_routine arg - (pthread_key_create): likewise for destructor arg - (ptw32_cleanup_push): replace type of routine arg with previously - defined ptw32_cleanup_callback_t - * pthread_key_create.c: add __cdecl attribute to destructor arg - * pthread_once.c: add __cdecl attribute to init_routine arg - * ptw32_threadStart.c (start): add __cdecl to start variable type - - -2011-07-06 Ross Johnson - - * pthread_cond_wait.c (pragma inline_depth): this is almost redundant - now nevertheless fixed thei controlling MSC_VER from "< 800" to - "< 1400" (i.e. any prior to VC++ 8.0). - * pthread_once.ci (pragma inline_depth): Likewise. - * pthread_rwlock_timedwrlock.ci (pragma inline_depth): Likewise. - * pthread_rwlock_wrlock.ci (pragma inline_depth): Likewise. - * sem_timedwait.ci (pragma inline_depth): Likewise. - * sem_wait.ci (pragma inline_depth): Likewise. - -2011-07-05 Ross Johnson - - * pthread_win32_attach_detach_np.c: Use strncat_s if available - to removei a compile warning; MingW supports this routine but we - continue to use strncat anyway there because it is secure if - given the correct parameters; fix strncat param 3 to avoid - buffer overrun exploitation potential. - -2011-07-03 Ross Johnson - - * pthread_spin_unlock.c (EPERM): Return success if unlocking a lock - that is not locked, because single CPU machines wrap a - PTHREAD_MUTEX_NORMAL mutex, which returns success in this case. - * pthread_win32_attach_detach_np.c (QUSEREX.DLL): Load from an - absolute path only which must be the Windows System folder. - -2011-07-03 Daniel Richard G. - - * Makefile (_WIN32_WINNT): Removed; duplicate definition in - implement.h; more cleanup and enhancements. - -2011-07-02 Daniel Richard G. - - * Makefile: Cleanups and implovements. - * ptw32_MCS_locks.c: Casting fixes. - * implement.h: Interlocked call and argument casting macro fixes - to support older and newer build environments. - -2011-07-01 Ross Johnson - - * *.[ch] (PTW32_INTERLOCKED_*): Redo 23 and 64 bit versions of these - macros and re-apply in code to undo the incorrect changes from - 2011-06-29; remove some size_t casts which should not be required - and may be problematic.a - There are now two sets of macros: - PTW32_INTERLOCKED_*_LONG which work only on 32 bit integer variables; - PTW32_INTERLOCKED_*_SIZE which work on size_t integer variables, i.e. - LONG for 32 bit systems and LONGLONG for 64 bit systems. - * implement.h (MCS locks): nextFlag and waitFlag are now HANDLE type. - * ptw32_MCS_locks.c: Likewise. - * pthread.h (#include ): Removed. - * ptw32_throw.c (#include ): Added. - * ptw32_threadStart.c (#include ): Added. - * implement.h (#include ): Added. - -2011-06-30 Ross Johnson - - * pthread_once.c: Tighten 'if' statement casting; fix interlocked - pointer cast for 64 bit compatibility (missed yesterday); remove - the superfluous static cleanup routine and call the release routine - directly if popped. - * create.c (stackSize): Now type size_t. - * pthread.h (struct ptw32_thread_t_): Rearrange to fix element alignments. - -2011-06-29 Daniel Richard G. - - * ptw32_relmillisecs.c (ftime): - _ftime64_s() is only available in MSVC 2005 or later; - _ftime64() is available in MinGW or MSVC 2002 or later; - _ftime() is always available. - * pthread.h (long long): Not defined in older MSVC 6. - * implement.h (long long): Likewise. - * pthread_getunique_np.c (long long): Likewise. - -2011-06-29 Ross Johnson - - * *.[ch] (PTW32_INTERLOCKED_*): These macros should now work for - both 32 and 64 bit builds. The MingW versions are all inlined asm - while the MSVC versions expand to their Interlocked* or Interlocked*64 - counterparts appropriately. The argument type have also been changed - to cast to the appropriate value or pointer size for the architecture. - -2011-05-29 Ross Johnson - - * *.[ch] (#ifdef): Extended cleanup to whole project. - -2011-05-29 Daniel Richard G. - - * Makefile (CC): Define CC to allow use of other compatible - compilers such as the Intel compilter icl. - * implement.h (#if): Fix forms like #if HAVE_SOMETHING. - * pthread.h: Likewise. - * sched.h: Likewise; PTW32_LEVEL_* becomes PTW32_SCHED_LEVEL_*. - * semaphore.h: Likewise. - -2011-05-11 Ross Johnson - - * ptw32_callUserDestroyRoutines.c (terminate): Altered includes - to match ptw32_threadStart.c. - * GNUmakefile (GCE-inlined-debug, DOPT): Fixed. - -2011-04-31 Ross Johnson - - * (robust mutexes): Added this API. The API is not - mandatory for implementations that don't support PROCESS_SHARED - mutexes, nevertheless it was considered useful both functionally - and for source-level compatibility. - -2011-03-26 Ross Johnson - - * pthread_getunique_np.c: New non-POSIX interface for compatibility - with some other implementations; returns a 64 bit sequence number - that is unique to each thread in the process. - * pthread.h (pthread_getunique_np): Added. - * global.c: Add global sequence counter for above. - * implement.h: Likewise. - -2011-03-25 Ross Johnson - - * (cancelLock): Convert to an MCS lock and rename to stateLock. - * (threadLock): Likewise. - * (keyLock): Likewise. - * pthread_mutex*.c: First working robust mutexes. - -2011-03-11 Ross Johnson - - * implement.h (PTW32_INTERLOCKED_*CREMENT macros): increment/decrement - using ++/-- instead of add/subtract 1. - * ptw32_MCS_lock.c: Make casts consistent. - -2011-03-09 Ross Johnson - - * implement.h (ptw32_thread_t_): Add process unique sequence number. - * global.c: Replace global Critical Section objects with MCS - queue locks. - * implement.h: Likewise. - * pthread_cond_destroy.c: Likewise. - * pthread_cond_init.c: Likewise. - * pthread_detach.c: Likewise. - * pthread_join.c: Likewise. - * pthread_kill.c: Likewise. - * pthread_mutex_destroy.c: Likewise. - * pthread_rwlock_destroy.c: Likewise. - * pthread_spin_destroy.c: Likewise. - * pthread_timechange_handler_np.c: Likewise. - * ptw32_cond_check_need_init.c: Likewise. - * ptw32_mutex_check_need_init.c: Likewise. - * ptw32_processInitialize.c: Likewise. - * ptw32_processTerminate.c: Likewise. - * ptw32_reuse.c: Likewise. - * ptw32_rwlock_check_need_init.c: Likewise. - * ptw32_spinlock_check_need_init.c: Likewise. - -2011-03-06 Ross Johnson - - * several (MINGW64): Cast and call fixups for 64 bit compatibility; - clean build via x86_64-w64-mingw32 cross toolchain on Linux i686 - targeting x86_64 win64. - * ptw32_threadStart.c (ptw32_threadStart): Routine no longer attempts - to pass [unexpected C++] exceptions out of scope but ends the thread - normally setting EINTR as the exit status. - * ptw32_throw.c: Fix C++ exception throwing warnings; ignore - informational warning. - * implement.h: Likewise with the corresponding header definition. - -2011-03-04 Ross Johnson - - * implement.h (PTW32_INTERLOCKED_*): Mingw32 does not provide - the __sync_* intrinsics so implemented them here as macro - assembler routines. MSVS Interlocked* are emmitted as intrinsics - wherever possible, so we want mingw to match it; Extended to - include all interlocked routines used by the library; implemented - x86_64 versions also. - * ptw32_InterlockedCompareExchange.c: No code remaining here. - * ptw32_MCS_lock.c: Converted interlocked calls to use new macros. - * pthread_barrier_wait.c: Likewise. - * pthread_once.c: Likewise. - * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): Name changed to - ptw32_mcs_node_transfer. - -2011-02-28 Ross Johnson - - * ptw32_relmillisecs.c: If possible, use _ftime64_s or _ftime64 - before resorting to _ftime. - -2011-02-27 Ross Johnson - - * sched_setscheduler.c: Ensure the handle is closed after use. - * sched_getscheduler.c: Likewise. - * pthread.h: Remove POSIX compatibility macros; don't define - timespec if already defined. - * context.h: Changes for 64 bit. - * pthread_cancel.c: Likewise. - * pthread_exit.c: Likewise. - * pthread_spin_destroy.c: Likewise. - * pthread_timechange_handler_np.c: Likewise. - * ptw32_MCS_lock.c: Likewise; some of these changes may - not be compatible with pre Windows 2000 systems; reverse the order of - the includes. - * ptw32_threadStart.c: Likewise. - * ptw32_throw.c: Likewise. - -2011-02-13 Ross Johnson - - * pthread_self: Add comment re returning 'nil' value to - indicate failure only to win32 threads that call us. - * pthread_attr_setstackaddr: Fix comments; note this - function and it's compliment are now removed from SUSv4. - -2011-02-12 Ross Johnson - - README.NONPORTABLE: Record a description of an obvious - method for nulling/comparing/hashing pthread_t using a - union; plus and investigation of a change of type for - pthread_t (to a union) to neutralise any padding bits and - bytes if they occur in pthread_t (the current pthread_t struct - does not contain padding AFAIK, but porting the library to a - future architecture may introduce them). Padding affects - byte-by-byte copies and compare operations. - -2010-11-16 Ross Johnson - - * ChangeLog: Add this entry ;-) - Restore entries from 2007 through 2009 that went missing - at the last update. - -2010-06-19 Ross Johnson - - * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): Fix variable - names to avoid using C++ keyword ("new"). - * implement.h (ptw32_mcs_node_substitute): Likewise. - * pthread_barrier_wait.c: Fix signed/unsigned comparison warning. - -2010-06-18 Ramiro Polla - - * autostatic.c: New file; call pthread_win32_process_*() - libary init/cleanup routines automatically on application start - when statically linked. - * pthread.c (autostatic.c): Included. - * pthread.h (declspec): Remove import/export defines if compiler - is MINGW. - * sched.h (declspec): Likewise. - * semaphore.h (declspec): Likewise. - * need_errno.h (declspec): Likewise. - * Makefile (autostatic.obj): Add for small static builds. - * GNUmakefile (autostatic.o): Likewise. - * NEWS (Version 2.9.0): Add changes. - * README.NONPORTABLE (pthread_win32_process_*): Update - description. - -2010-06-15 Ramiro Polla - - * Makefile: Remove linkage with the winsock library by default. - * GNUmakefile: Likewise. - * pthread_getspecific.c: Likewise by removing calls to WSA - functions. - * config.h (RETAIN_WSALASTERROR): Can be defined if necessary. - -2010-01-26 Ross Johnson - - * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): New routine - to allow relocating the lock owners thread-local node to somewhere - else, e.g. to global space so that another thread can release the - lock. Used in pthread_barrier_wait. - (ptw32_mcs_lock_try_acquire): New routine. - * pthread_barrier_init: Only one semaphore is used now. - * pthread_barrier_wait: Added an MCS guard lock with the last thread - to leave the barrier releasing the lock. This removes a deadlock bug - observed when there are greater than barrier-count threads - attempting to cross. - * pthread_barrier_destroy: Added an MCS guard lock. - -2009-03-03 Stephan O'Farrill - - * pthread_attr_getschedpolicy.c: Add "const" to function parameter - in accordance with SUSv3 (POSIX). - * pthread_attr_getinheritsched.c: Likewise. - * pthread_mutexattr_gettype.c: Likewise. - -2008-06-06 Robert Kindred - - * ptw32_throw.c (ptw32_throw): Remove possible reference to NULL - pointer. (At the same time made the switch block conditionally - included only if exitCode is needed - RPJ.) - * pthread_testcancel.c (pthread_testcancel): Remove duplicate and - misplaced pthread_mutex_unlock(). - -2008-02-21 Sebastian Gottschalk - - * pthread_attr_getdetachstate.c (pthread_attr_getdetachstate): - Remove potential and superfluous null pointer assignment. - -2007-11-22 Ivan Pizhenko - - * pthread.h (gmtime_r): gmtime returns 0 if tm represents a time - prior to 1/1/1970. Notice this to prevent raising an exception. - * pthread.h (localtime_r): Likewise for localtime. - -2007-07-14 Marcel Ruff - - * errno.c (_errno): Fix test for pthread_self() success. - * need_errno.h: Remove unintentional line wrap from #if line. - -2007-07-14 Mike Romanchuk - - * pthread.h (timespec): Fix tv_sec type. - -2007-01-07 Sinan Kaya - - * need_errno.h: Fix declaration of _errno - the local version of - _errno() is used, e.g. by WinCE. - -2007-01-06 Ross Johnson - - * ptw32_semwait.c: Add check for invalid sem_t after acquiring the - sem_t state guard mutex and before affecting changes to sema state. - -2007-01-06 Marcel Ruff - - * error.c: Fix reference to pthread handle exitStatus member for - builds that use NEED_ERRNO (i.e. WINCE). - * context.h: Add support for ARM processor (WinCE). - * mutex.c (process.h): Exclude for WINCE. - * create.c: Likewise. - * exit.c: Likewise. - * implement.h: Likewise. - * pthread_detach.c (signal.h): Exclude for WINCE. - * pthread_join.c: Likewise. - * pthread_kill.c: Likewise. - * pthread_rwlock_init.c (errno.h): Remove - included by pthread.h. - * pthread_rwlock_destroy.c: Likewise. - * pthread_rwlock_rdlock.c: Likewise. - * pthread_rwlock_timedrdlock.c: Likewise. - * pthread_rwlock_timedwrlock.c: Likewise. - * pthread_rwlock_tryrdlock.c: Likewise. - * pthread_rwlock_trywrlock.c: likewise. - * pthread_rwlock_unlock.c: Likewise. - * pthread_rwlock_wrlock.c: Likewise. - * pthread_rwlockattr_destroy.c: Likewise. - * pthread_rwlockattr_getpshared.c: Likewise. - * pthread_rwlockattr_init.c: Likewise. - * pthread_rwlockattr_setpshared.c: Likewise. - -2007-01-06 Romano Paolo Tenca - - * pthread_cond_destroy.c: Replace sem_wait() with non-cancelable - ptw32_semwait() since pthread_cond_destroy() is not a cancelation - point. - * implement.h (ptw32_spinlock_check_need_init): Add prototype. - * ptw32_MCS_lock.c: Reverse order of includes. - -2007-01-06 Eric Berge - - * pthread_cond_destroy.c: Add LeaveCriticalSection before returning - after errors. - -2007-01-04 Ross Johnson - - * ptw32_InterlockedCompareExchange.c: Conditionally skip for - Win64 as not required. - * pthread_win32_attach_detach_np.c (pthread_win32_process_attach_np): - Test for InterlockedCompareExchange is not required for Win64. - * context.h: New file. Included by pthread_cancel.h and any tests - that need it (e.g. context1.c). - * pthread_cancel.c: Architecture-dependent context macros moved - to context.h. - -2007-01-04 Kip Streithorst - - * implement.h (PTW32_INTERLOCKED_COMPARE_EXCHANGE): Add Win64 - support. - -2006-12-20 Ross Johnson - - * sem_destroy.c: Fix the race involving invalidation of the sema; - fix incorrect return of EBUSY resulting from the mutex trylock - on the private mutex guard. - * sem_wait.c: Add check for invalid sem_t after acquiring the - sem_t state guard mutex and before affecting changes to sema state. - * sem_trywait.c: Likewise. - * sem_timedwait.c: Likewise. - * sem_getvalue.c: Likewise. - * sem_post.c: Similar. - * sem_post_multiple.c: Likewise. - * sem_init.c: Set max Win32 semaphore count to SEM_VALUE_MAX (was - _POSIX_SEM_VALUE_MAX, which is a lower value - the minimum). - - * pthread_win32_attach_detach_np.c (pthread_win32_process_attach_np): - Load COREDLL.DLL under WINCE to check existence of - InterlockedCompareExchange() routine. This used to be done to test - for TryEnterCriticalSection() but was removed when this was no - longer needed. - -2006-01-25 Prashant Thakre - - * pthread_cancel.c: Added _M_IA64 register context support. - -2005-05-13 Ross Johnson - - * pthread_kill.c (pthread_kill): Remove check for Win32 thread - priority (to confirm HANDLE validity). Useless since thread HANDLEs - a not recycle-unique. - -2005-05-30 Vladimir Kliatchko - - * pthread_once.c: Re-implement using an MCS queue-based lock. The form - of pthread_once is as proposed by Alexander Terekhov (see entry of - 2005-03-13). The MCS lock implementation does not require a unique - 'name' to identify the lock between threads. Attempts to get the Event - or Semaphore based versions of pthread_once to a satisfactory level - of robustness have thus far failed. The last problem (avoiding races - involving non recycle-unique Win32 HANDLEs) was giving everyone - grey hair trying to solve it. - - * ptw32_MCS_lock.c: New MCS queue-based lock implementation. These - locks are efficient: they have very low overhead in the uncontended case; - are efficient in contention and minimise cache-coherence updates in - managing the user level FIFO queue; do not require an ABI change in the - library. - -2005-05-27 Alexander Gottwald - - * pthread.h: Some things, like HANDLE, were only defined if - PTW32_LEVEL was >= 3. They should always be defined. - -2005-05-25 Vladimir Kliatchko - - * pthread_once.c: Eliminate all priority operations and other - complexity by replacing the event with a semaphore. The advantage - of the change is the ability to release just one waiter if the - init_routine thread is cancelled yet still release all waiters when - done. Simplify once_control state checks to improve efficiency - further. - -2005-05-24 Mikael Magnusson - - * GNUmakefile: Patched to allow cross-compile with mingw32 on Linux. - It uses macros instead of referencing dlltool, gcc and g++ directly; - added a call to ranlib. For example the GC static library can be - built with: - make CC=i586-mingw32msvc-gcc RC=i586-mingw32msvc-windres \ - RANLIB=i586-mingw32msvc-ranlib clean GC-static - -2005-05-13 Ross Johnson - - * pthread_win32_attach_detach_np.c (pthread_win32_thread_detach_np): - Move on-exit-only stuff from ptw32_threadDestroy() to here. - * ptw32_threadDestroy.c: It's purpose is now only to reclaim thread - resources for detached threads, or via pthread_join() or - pthread_detach() on joinable threads. - * ptw32_threadStart.c: Calling user destruct routines has moved to - pthread_win32_thread_detach_np(); call pthread_win32_thread_detach_np() - directly if statically linking, otherwise do so via dllMain; store - thread return value in thread struct for all cases, including - cancellation and exception exits; thread abnormal exits go via - pthread_win32_thread_detach_np. - * pthread_join.c (pthread_join): Don't try to get return code from - Win32 thread - always get it from he thread struct. - * pthread_detach.c (pthread_detach): reduce extent of the thread - existence check since we now don't care if the Win32 thread HANDLE has - been closed; reclaim thread resources if the thread has exited already. - * ptw32_throw.c (ptw32_throw): For Win32 threads that are not implicit, - only Call thread cleanup if statically linking, otherwise leave it to - dllMain. - * sem_post.c (_POSIX_SEM_VALUE_MAX): Change to SEM_VALUE_MAX. - * sem_post_multiple.c: Likewise. - * sem_init.c: Likewise. - -2005-05-10 Ross Johnson - - * pthread_join.c (pthread_join): Add missing check for thread ID - reference count in thread existence test; reduce extent of the - existence test since we don't care if the Win32 thread HANDLE has - been closed. - -2005-05-09 Ross Johnson - - * ptw32_callUserDestroyRoutines.c: Run destructor process (i.e. - loop over all keys calling destructors) up to - PTHREAD_DESTRUCTOR_ITERATIONS times if TSD value isn't NULL yet; - modify assoc management. - * pthread_key_delete.c: Modify assoc management. - * ptw32_tkAssocDestroy.c: Fix error in assoc removal from chains. - * pthread.h - (_POSIX_THREAD_DESTRUCTOR_ITERATIONS): Define to value specified by - POSIX. - (_POSIX_THREAD_KEYS_MAX): Define to value specified by POSIX. - (PTHREAD_KEYS_MAX): Redefine [upward] to minimum required by POSIX. - (SEM_NSEMS_MAX): Define to implementation value. - (SEM_VALUE_MAX): Define to implementation value. - (_POSIX_SEM_NSEMS_MAX): Redefine to value specified by POSIX. - (_POSIX_SEM_VALUE_MAX): Redefine to value specified by POSIX. - -2005-05-06 Ross Johnson - - * signal.c (sigwait): Add a cancellation point to this otherwise - no-op. - * sem_init.c (sem_init): Check for and return ERANGE error. - * sem_post.c (sem_post): Likewise. - * sem_post_multiple.c (sem_post_multiple): Likewise. - * manual (directory): Added; see ChangeLog inside. - -2005-05-02 Ross Johnson - - * implement.h (struct pthread_key_t_): Change threadsLock to keyLock - so as not to be confused with the per thread lock 'threadlock'; - change all references to it. - * implement.h (struct ThreadKeyAssoc): Remove lock; add prevKey - and prevThread pointers; re-implemented all routines that use this - struct. The effect of this is to save one handle per association, - which could potentially equal the number of keys multiplied by the - number of threads, accumulating over time - and to free the - association memory as soon as it is no longer referenced by either - the key or the thread. Previously, the handle and memory were - released only after BOTH key and thread no longer referenced the - association. That is, often no association resources were released - until the process itself exited. In addition, at least one race - condition has been removed - where two threads could attempt to - release the association resources simultaneously - one via - ptw32_callUserDestroyRoutines and the other via - pthread_key_delete. - - thanks to Richard Hughes at Aculab for discovering the problem. - * pthread_key_create.c: See above. - * pthread_key_delete.c: See above. - * pthread_setspecific.c: See above. - * ptw32_callUserDestroyRoutines.c: See above. - * ptw32_tkAssocCreate.c: See above. - * ptw32_tkAssocDestroy.c: See above. - -2005-04-27 Ross Johnson - - * sem_wait.c (ptw32_sem_wait_cleanup): after cancellation re-attempt - to acquire the semaphore to avoid a race with a late sem_post. - * sem_timedwait.c: Modify comments. - -2005-04-25 Ross Johnson - - * ptw32_relmillisecs.c: New module; converts future abstime to - milliseconds relative to 'now'. - * pthread_mutex_timedlock.c: Use new ptw32_relmillisecs routine in - place of internal code; remove the NEED_SEM code - this routine is now - implemented for builds that define NEED_SEM (WinCE etc) - * sem_timedwait.c: Likewise; after timeout or cancellation, - re-attempt to acquire the semaphore in case one has been posted since - the timeout/cancel occurred. Thanks to Stefan Mueller. - * Makefile: Add ptw32_relmillisecs.c module; remove - ptw32_{in,de}crease_semaphore.c modules. - * GNUmakefile: Likewise. - * Bmakefile: Likewise. - - * sem_init.c: Re-write the NEED_SEM code to be consistent with the - non-NEED_SEM code, but retaining use of an event in place of the w32 sema - for w32 systems that don't include semaphores (WinCE); - the NEED_SEM versions of semaphores has been broken for a long time but is - now fixed and supports all of the same routines as the non-NEED_SEM case. - * sem_destroy.c: Likewise. - * sem_wait.c: Likewise. - * sem_post.c: Likewise. - * sem_post_multple.c: Likewise. - * implement.h: Likewise. - * sem_timedwait.c: Likewise; this routine is now - implemented for builds that define NEED_SEM (WinCE etc). - * sem_trywait.c: Likewise. - * sem_getvalue.c: Likewise. - - * pthread_once.c: Yet more changes, reverting closer to Gottlob Frege's - first design, but retaining cancellation, priority boosting, and adding - preservation of W32 error codes to make pthread_once transparent to - GetLastError. - -2005-04-11 Ross Johnson - - * pthread_once.c (pthread_once): Added priority boosting to - solve starvation problem after once_routine cancellation. - See notes in file. - -2005-04-06 Kevin Lussier - - * Makefile: Added debug targets for all versions of the library. - -2005-04-01 Ross Johnson - - * GNUmakefile: Add target to build libpthreadGC1.a as a static link - library. - * Makefile: Likewise for pthreadGC1.lib. - -2005-04-01 Kevin Lussier - - * sem_timedwait.c (sem_timedwait): Increase size of temp variables to - avoid int overflows for large timeout values. - * implement.h (int64_t): Include or define. - -2005-03-31 Dimitar Panayotov ^M - - * pthread.h: Fix conditional defines for static linking. - * sched.h: Liekwise. - * semaphore.h: Likewise. - * dll.c (PTW32_STATIC_LIB): Module is conditionally included - in the build. - -2005-03-16 Ross Johnson ^M - - * pthread_setcancelstate.c: Undo the last change. - -2005-03-16 Ross Johnson ^M - - * pthread_setcancelstate.c: Don't check for an async cancel event - if the library is using alertable async cancel.. - -2005-03-14 Ross Johnson - - * pthread_once.c (pthread_once): Downgrade interlocked operations to simple - memory operations where these are protected by the critical section; edit - comments. - -2005-03-13 Ross Johnson - - * pthread_once.c (pthread_once): Completely redesigned; a change was - required to the ABI (pthread_once_t_), and resulting in a version - compatibility index increment. - - NOTES: - The design (based on pseudo code contributed by Gottlob Frege) avoids - creating a kernel object if there is no contention. See URL for details:- - http://sources.redhat.com/ml/pthreads-win32/2005/msg00029.html - This uses late initialisation similar to the technique already used for - pthreads-win32 mutexes and semaphores (from Alexander Terekhov). - - The subsequent cancelation cleanup additions (by rpj) could not be implemented - without sacrificing some of the efficiency in Gottlob's design. In particular, - although each once_control uses it's own event to block on, a global CS is - required to manage it - since the event must be either re-usable or - re-creatable under cancelation. This is not needed in the non-cancelable - design because it is able to mark the event as closed (forever). - - When uncontested, a CS operation is equivalent to an Interlocked operation - in speed. So, in the final design with cancelability, an uncontested - once_control operation involves a minimum of five interlocked operations - (including the LeaveCS operation). - - ALTERNATIVES: - An alternative design from Alexander Terekhov proposed using a named mutex, - as sketched below:- - - if (!once_control) { // May be in TLS - named_mutex::guard guard(&once_control2); - if (!once_control2) { - - once_control2 = true; - } - once_control = true; - } - - A more detailed description of this can be found here:- - http://groups.yahoo.com/group/boost/message/15442 - - [Although the definition of a suitable PTHREAD_ONCE_INIT precludes use of the - TLS located flag, this is not critical.] - - There are three primary concerns though:- - 1) The [named] mutex is 'created' even in the uncontended case. - 2) A system wide unique name must be generated. - 3) Win32 mutexes are VERY slow even in the uncontended case. An uncontested - Win32 mutex lock operation can be 50 (or more) times slower than an - uncontested EnterCS operation. - - Ultimately, the named mutex trick is making use of the global locks maintained - by the kernel. - - * pthread.h (pthread_once_t_): One flag and an event HANDLE added. - (PTHREAD_ONCE_INIT): Additional values included. - -2005-03-08 Ross Johnson - - * pthread_once.c (pthread_once): Redesigned to elliminate potential - starvation problem. - - reported by Gottlob Frege - - * ptw32_threadDestroy.c (ptw32_threadDestroy): Implicit threads were - not closing their Win32 thread duplicate handle. - - reported by Dmitrii Semii - -2005-01-25 Ralf Kubis - - * Attempted acquisition of recursive mutex was causing waiting - threads to not be woken when the mutex is released. - - * GNUmakefile (GCE): Generate correct version resource comments. - -2005-01-01 Konstantin Voronkov - - * pthread_mutex_lock.c (pthread_mutex_lock): The new atomic exchange - mutex algorithm is known to allow a thread to steal the lock off - FIFO waiting threads. The next waiting FIFO thread gets a spurious - wake-up and must attempt to re-acquire the lock. The woken thread - was setting itself as the mutex's owner before the re-acquisition. - -2004-11-22 Ross Johnson - - * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Undo change - from 2004-11-02. - * Makefile (DLL_VER): Added for DLL naming suffix - see README. - * GNUmakefile (DLL_VER): Likewise. - * Wmakefile (DLL_VER): Likewise. - * Bmakefile (DLL_VER): Likewise. - * pthread.dsw (version.rc): Added to MSVS workspace. - -2004-11-20 Boudewijn Dekker - - * pthread_getspecific.c (pthread_getspecific): Check for - invalid (NULL) key argument. - -2004-11-19 Ross Johnson - - * config.h (PTW32_THREAD_ID_REUSE_INCREMENT): Added to allow - building the library for either unique thread IDs like Solaris - or non-unique thread IDs like Linux; allows application developers - to override the library's default insensitivity to some apps - that may not be strictly POSIX compliant. - * version.rc: New resource module to encode version information - within the DLL. - * pthread.h: Added PTW32_VERSION* defines and grouped sections - required by resource compiler together; bulk of file is skipped - if RC_INVOKED. Defined some error numbers and other names for - Borland compiler. - -2004-11-02 Ross Johnson - - * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Lock CV mutex at - start of cleanup handler rather than at the end. - * implement.h (PTW32_THREAD_REUSE_EMPTY): Renamed from *_BOTTOM. - (ptw32_threadReuseBottom): New global variable. - * global.c (ptw32_threadReuseBottom): Declare new variable. - * ptw32_reuse.c (ptw32_reuse): Change reuse LIFO stack to LILO queue - to more evenly distribute use of reusable thread IDs; use renamed - PTW32_THREAD_REUSE_EMPTY. - * ptw32_processTerminate.c (ptw2_processTerminate): Use renamed - PTW32_THREAD_REUSE_EMPTY. - -2004-10-31 Ross Johnson - - * implement.h (PThreadState): Add new state value - 'PThreadStateCancelPending'. - * pthread_testcancel.c (pthread_testcancel): Use new thread - 'PThreadStateCancelPending' state as short cut to avoid entering - kernel space via WaitForSingleObject() call. This was obviated - by user space sema acquisition in sem_wait() and sem_timedwait(), - which are also cancelation points. A call to pthread_testcancel() - was required, which introduced a kernel call, effectively nullifying - any gains made by the user space sem acquisition checks. - * pthread_cancel.c (pthread_cancel): Set new thread - 'PThreadStateCancelPending' state. - -2004-10-29 Ross Johnson - - * implement.h (pthread_t): Renamed to ptw32_thread_t; struct contains - all thread state. - * pthread.h (ptw32_handle_t): New general purpose struct to serve - as a handle for various reusable object IDs - currently only used - by pthread_t; contains a pointer to ptw32_thread_t (thread state) - and a general purpose uint for use as a reuse counter or flags etc. - (pthread_t): typedef'ed to ptw32_handle_t; the uint is the reuse - counter that allows the library to maintain unique POSIX thread IDs. - When the pthread struct reuse stack was introduced, threads would - often acquire an identical ID to a previously destroyed thread. The - same was true for the pre-reuse stack library, by virtue of pthread_t - being the address of the thread struct. The new pthread_t retains - the reuse stack but provides virtually unique thread IDs. - * sem_wait.c (ptw32_sem_wait_cleanup): New routine used for - cancelation cleanup. - * sem_timedwait.c (ptw32_sem_timedwait_cleanup): Likewise. - -2004-10-22 Ross Johnson - - * sem_init.c (sem_init): Introduce a 'lock' element in order to - replace the interlocked operations with conventional serialisation. - This is needed in order to be able to atomically modify the sema - value and perform Win32 sema release operations. Win32 semaphores are - used instead of events in order to support efficient multiple posting. - If the whole modify/release isn't atomic, a race between - sem_timedwait() and sem_post() could result in a release when there is - no waiting semaphore, which would cause too many threads to proceed. - * sem_wait.c (sem_wait): Use new 'lock'element. - * sem_timedwait.c (sem_timedwait): Likewise. - * sem_trywait.c (sem_trywait): Likewise. - * sem_post.c (sem_post): Likewise. - * sem_post_multiple.c (sem_post_multiple): Likewise. - * sem_getvalue.c (sem_getvalue): Likewise. - * ptw32_semwait.c (ptw32_semwait): Likewise. - * sem_destroy.c (sem_destroy): Likewise; also tightened the conditions - for semaphore destruction; in particular, a semaphore will not be - destroyed if it has waiters. - * sem_timedwait.c (sem_timedwait): Added cancel cleanup handler to - restore sema value when cancelled. - * sem_wait.c (sem_wait): Likewise. - -2004-10-21 Ross Johnson - - * pthread_mutex_unlock.c (pthread_mutex_unlock): Must use PulseEvent() - rather than SetEvent() to reset the event if there are no waiters. - -2004-10-19 Ross Johnson - - * sem_init.c (sem_init): New semaphore model based on the same idea - as mutexes, i.e. user space interlocked check to avoid - unnecessarily entering kernel space. Wraps the Win32 semaphore and - keeps it's own counter. Although the motivation to do this has existed - for a long time, credit goes to Alexander Terekhov for providing - the logic. I have deviated slightly from AT's logic to add the waiters - count, which has made the code more complicated by adding cancelation - cleanup. This also appears to have broken the VCE (C++ EH) version of - the library (the same problem as previously reported - see BUGS #2), - only apparently not fixable using the usual workaround, nor by turning - all optimisation off. The GCE version works fine, so it is presumed to - be a bug in MSVC++ 6.0. The cancelation exception is thrown and caught - correctly, but the cleanup class destructor is never called. The failing - test is tests\semaphore4.c. - * sem_wait.c (sem_wait): Implemented user space check model. - * sem_post.c (sem_post): Likewise. - * sem_trywait.c (sem_trywait): Likewise. - * sem_timedwait.c (sem_timedwait): Likewise. - * sem_post_multiple.c (sem_post_multiple): Likewise. - * sem_getvalue.c (sem_getvalue): Likewise. - * ptw32_semwait.c (ptw32_semwait): Likewise. - * implement.h (sem_t_): Add counter element. - -2004-10-15 Ross Johnson - - * implement.h (pthread_mutex_t_): Use an event in place of - the POSIX semaphore. - * pthread_mutex_init.c: Create the event; remove semaphore init. - * pthread_mutex_destroy.c: Delete the event. - * pthread_mutex_lock.c: Replace the semaphore wait with the event wait. - * pthread_mutex_trylock.c: Likewise. - * pthread_mutex_timedlock.c: Likewise. - * pthread_mutex_unlock.c: Set the event. - -2004-10-14 Ross Johnson - - * pthread_mutex_lock.c (pthread_mutex_lock): New algorithm using - Terekhov's xchg based variation of Drepper's cmpxchg model. - Theoretically, xchg uses fewer clock cycles than cmpxchg (using IA-32 - as a reference), however, in my opinion bus locking dominates the - equation on smp systems, so the model with the least number of bus - lock operations in the execution path should win, which is Terekhov's - variant. On IA-32 uni-processor systems, it's faster to use the - CMPXCHG instruction without locking the bus than to use the XCHG - instruction, which always locks the bus. This makes the two variants - equal for the non-contended lock (fast lane) execution path on up - IA-32. Testing shows that the xchg variant is faster on up IA-32 as - well if the test forces higher lock contention frequency, even though - kernel calls should be dominating the times (on up IA-32, both - variants used CMPXCHG instructions and neither locked the bus). - * pthread_mutex_timedlock.c pthread_mutex_timedlock(): Similarly. - * pthread_mutex_trylock.c (pthread_mutex_trylock): Similarly. - * pthread_mutex_unlock.c (pthread_mutex_unlock): Similarly. - * ptw32_InterlockedCompareExchange.c (ptw32_InterlockExchange): New - function. - (PTW32_INTERLOCKED_EXCHANGE): Sets up macro to use inlined - ptw32_InterlockedExchange. - * implement.h (PTW32_INTERLOCKED_EXCHANGE): Set default to - InterlockedExchange(). - * Makefile: Building using /Ob2 so that asm sections within inline - functions are inlined. - -2004-10-08 Ross Johnson - - * pthread_mutex_destroy.c (pthread_mutex_destroy): Critical Section - element is no longer required. - * pthread_mutex_init.c (pthread_mutex_init): Likewise. - * pthread_mutex_lock.c (pthread_mutex_lock): New algorithm following - Drepper's paper at http://people.redhat.com/drepper/futex.pdf, but - using the existing semaphore in place of the futex described in the - paper. Idea suggested by Alexander Terekhov - see: - http://sources.redhat.com/ml/pthreads-win32/2003/msg00108.html - * pthread_mutex_timedlock.c pthread_mutex_timedlock(): Similarly. - * pthread_mutex_trylock.c (pthread_mutex_trylock): Similarly. - * pthread_mutex_unlock.c (pthread_mutex_unlock): Similarly. - * pthread_barrier_wait.c (pthread_barrier_wait): Use inlined version - of InterlockedCompareExchange() if possible - determined at - build-time. - * pthread_spin_destroy.c pthread_spin_destroy(): Likewise. - * pthread_spin_lock.c pthread_spin_lock():Likewise. - * pthread_spin_trylock.c (pthread_spin_trylock):Likewise. - * pthread_spin_unlock.c (pthread_spin_unlock):Likewise. - * ptw32_InterlockedCompareExchange.c: Sets up macro for inlined use. - * implement.h (pthread_mutex_t_): Remove Critical Section element. - (PTW32_INTERLOCKED_COMPARE_EXCHANGE): Set to default non-inlined - version of InterlockedCompareExchange(). - * private.c: Include ptw32_InterlockedCompareExchange.c first for - inlining. - * GNUmakefile: Add commandline option to use inlined - InterlockedCompareExchange(). - * Makefile: Likewise. - -2004-09-27 Ross Johnson - - * pthread_mutex_lock.c (pthread_mutex_lock): Separate - PTHREAD_MUTEX_NORMAL logic since we do not need to keep or check some - state required by other mutex types; do not check mutex pointer arg - for validity - leave this to the system since we are only checking - for NULL pointers. This should improve speed of NORMAL mutexes and - marginally improve speed of other type. - * pthread_mutex_trylock.c (pthread_mutex_trylock): Likewise. - * pthread_mutex_unlock.c (pthread_mutex_unlock): Likewise; also avoid - entering the critical section for the no-waiters case, with approx. - 30% reduction in lock/unlock overhead for this case. - * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Likewise; also - no longer keeps mutex if post-timeout second attempt succeeds - this - will assist applications that wish to impose strict lock deadlines, - rather than simply to escape from frozen locks. - -2004-09-09 Tristan Savatier - * pthread.h (struct pthread_once_t_): Qualify the 'done' element - as 'volatile'. - * pthread_once.c: Concerned about possible race condition, - specifically on MPU systems re concurrent access to multibyte types. - [Maintainer's note: the race condition is harmless on SPU systems - and only a problem on MPU systems if concurrent access results in an - exception (presumably generated by a hardware interrupt). There are - other instances of similar harmless race conditions that have not - been identified as issues.] - -2004-09-09 Ross Johnson - - * pthread.h: Declare additional types as volatile. - -2004-08-27 Ross Johnson - - * pthread_barrier_wait.c (pthread_barrier_wait): Remove excessive code - by substituting the internal non-cancelable version of sem_wait - (ptw32_semwait). - -2004-08-25 Ross Johnson - - * pthread_join.c (pthread_join): Rewrite and re-order the conditional - tests in an attempt to improve efficiency and remove a race - condition. - -2004-08-23 Ross Johnson - - * create.c (pthread_create): Don't create a thread if the thread - id pointer location (first arg) is inaccessible. A memory - protection fault will result if the thread id arg isn't an accessible - location. This is consistent with GNU/Linux but different to - Solaris or MKS (and possibly others), which accept NULL as meaning - 'don't return the created thread's ID'. Applications that run - using pthreads-win32 will run on all other POSIX threads - implementations, at least w.r.t. this feature. - - It was decided not to copy the Solaris et al behaviour because, - although it would have simplified some application porting (but only - from Solaris to Windows), the feature is not technically necessary, - and the alternative segfault behaviour helps avoid buggy application - code. - -2004-07-01 Anuj Goyal - - * builddmc.bat: New; Windows bat file to build the library. - * config.h (__DMC__): Support for Digital Mars compiler. - * create.c (__DMC__): Likewise. - * pthread_exit.c (__DMC__): Likewise. - * pthread_join.c (__DMC__): Likewise. - * ptw32_threadDestroy.c (__DMC__): Likewise. - * ptw32_threadStart.c (__DMC__): Likewise. - * ptw32_throw.c (__DMC__): Likewise. - -2004-06-29 Anuj Goyal - - * pthread.h (__DMC__): Initial support for Digital Mars compiler. - -2004-06-29 Will Bryant - - * README.Borland: New; description of Borland changes. - * Bmakefile: New makefile for the Borland make utility. - * ptw32_InterlockedCompareExchange.c: - Add Borland compatible asm code. - -2004-06-26 Jason Bard - - * pthread.h (HAVE_STRUCT_TIMESPEC): If undefined, define it - to avoid timespec struct redefined errors elsewhere in an - application. - -2004-06-21 Ross Johnson - - * pthread.h (PTHREAD_RECURSIVE_MUTEX_INITIALIZER): Mutex - initialiser added for compatibility with Linux threads and - others; currently not included in SUSV3. - * pthread.h (PTHREAD_ERRORCHECK_MUTEX_INITIALIZER): Likewise. - * pthread.h (PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP): Likewise. - * pthread.h (PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP): Likewise. - - * ptw32_mutex_check_need_init.c (ptw32_mutex_check_need_init): - Add new initialisers. - - * pthread_mutex_lock.c (pthread_mutex_lock): Check for new - initialisers. - * pthread_mutex_trylock.c (pthread_mutex_trylock): Likewise. - * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Likewise. - * pthread_mutex_unlock.c (pthread_mutex_unlock): Likewise. - * pthread_mutex_destroy.c (pthread_mutex_destroy): Likewise. - -2004-05-20 Ross Johnson - - * README.NONPORTABLE: Document pthread_win32_test_features_np(). - * FAQ: Update various answers. - -2004-05-19 Ross Johnson - - * Makefile: Don't define _WIN32_WINNT on compiler command line. - * GNUmakefile: Likewise. - -2004-05-16 Ross Johnson - - * pthread_cancel.c (pthread_cancel): Adapted to use auto-detected - QueueUserAPCEx features at run-time. - (ptw32_RegisterCancelation): Drop in replacement for QueueUserAPCEx() - if it can't be used. Provides older style non-preemptive async - cancelation. - * pthread_win32_attach_detach_np.c (pthread_win32_attach_np): - Auto-detect quserex.dll and the availability of alertdrv.sys; - initialise and close on process attach/detach. - * global.c (ptw32_register_cancelation): Pointer to either - QueueUserAPCEx() or ptw32_RegisterCancelation() depending on - availability. QueueUserAPCEx makes pre-emptive async cancelation - possible. - * implement.h: Add definitions and prototypes related to QueueUserAPC. - -2004-05-16 Panagiotis E. Hadjidoukas - - * QueueUserAPCEx (separate contributed package): Provides preemptive - APC feature. - * pthread_cancel.c (pthread_cancel): Initial integration of - QueueUserAPCEx into pthreads-win32 to provide true pre-emptive - async cancelation of threads, including blocked threads. - -2004-05-06 Makoto Kato - - * pthread.h (DWORD_PTR): Define typedef for older MSVC. - * pthread_cancel.c (AMD64): Add architecture specific Context register. - * ptw32_getprocessors.c: Use correct types (DWORD_PTR) for mask - variables. - -2004-04-06 P. van Bruggen - - * ptw32_threadDestroy.c: Destroy threadLock mutex to - close a memory leak. - -2004-02-13 Gustav Hallberg - - * pthread_equal.c: Remove redundant equality logic. - -2003-12-10 Philippe Di Cristo - - * sem_timedwait.c (sem_timedwait): Fix timeout calculations. - -2003-10-20 Alexander Terekhov - - * pthread_mutex_timedlock.c (ptw32_semwait): Move to individual module. - * ptw32_semwait.c: New module. - * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Replace cancelable - sem_wait() call with non-cancelable ptw32_semwait() call. - * pthread.c (private.c): Re-order for inlining. GNU C warned that - function ptw32_semwait() was defined 'inline' after it was called. - * pthread_cond_signal.c (ptw32_cond_unblock): Likewise. - * pthread_delay_np.c: Disable Watcom warning with comment. - * *.c (process.h): Remove include from .c files. This is conditionally - included by the common project include files. - -2003-10-20 James Ewing - - * ptw32_getprocessors.c: Some Win32 environments don't have - GetProcessAffinityMask(), so always return CPU count = 1 for them. - * config.h (NEED_PROCESSOR_AFFINITY_MASK): Define for WinCE. - -2003-10-15 Ross Johnson - - * Re-indented all .c files using default GNU style to remove assorted - editor ugliness (used GNU indent utility in default style). - -2003-10-15 Alex Blanco - - * sem_init.c (sem_init): Would call CreateSemaphore even if the sema - struct calloc failed; was not freeing calloced memory if either - CreateSemaphore or CreateEvent failed. - -2003-10-14 Ross Johnson - - * pthread.h: Add Watcom compiler compatibility. Esssentially just add - the cdecl attribute to all exposed function prototypes so that Watcom - generates function call code compatible with non-Watcom built libraries. - By default, Watcom uses registers to pass function args if possible rather - than pushing to stack. - * semaphore.h: Likewise. - * sched.h: Likewise. - * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Define with cdecl attribute - for Watcom compatibility. This routine is called via pthread_cleanup_push so - it had to match function arg definition. - * Wmakefile: New makefile for Watcom builds. - -2003-09-14 Ross Johnson - - * pthread_setschedparam.c (pthread_setschedparam): Attempt to map - all priority levels between max and min (as returned by - sched_get_priority_min/max) to reasonable Win32 priority levels - i.e. - levels between THREAD_PRIORITY_LOWEST/IDLE to THREAD_PRIORITY_LOWEST and - between THREAD_PRIORITY_HIGHEST/TIME_CRITICAL to THREAD_PRIORITY_HIGHEST - while others remain unchanged; record specified thread priority level - for return by pthread_getschedparam. - - Note that, previously, specified levels not matching Win32 priority levels - would silently leave the current thread priority unaltered. - - * pthread_getschedparam.c (pthread_getschedparam): Return the priority - level specified by the latest pthread_setschedparam or pthread_create rather - than the actual running thread priority as returned by GetThreadPriority - as - required by POSIX. I.e. temporary or adjusted actual priority levels are not - returned by this routine. - - * pthread_create.c (pthread_create): For priority levels specified via - pthread attributes, attempt to map all priority levels between max and - min (as returned by sched_get_priority_min/max) to reasonable Win32 - priority levels; record priority level given via attributes, or - inherited from parent thread, for later return by pthread_getschedparam. - - * ptw32_new.c (ptw32_new): Initialise pthread_t_ sched_priority element. - - * pthread_self.c (pthread_self): Set newly created implicit POSIX thread - sched_priority to Win32 thread's current actual priority. Temporarily - altered priorities can't be avoided in this case. - - * implement.h (struct pthread_t_): Add new sched_priority element. - -2003-09-12 Ross Johnson - - * sched_get_priority_min.c (sched_get_priority_min): On error should return -1 - with errno set. - * sched_get_priority_max.c (sched_get_priority_max): Likewise. - -2003-09-03 Ross Johnson - - * w32_cancelableWait.c (ptw32_cancelable_wait): Allow cancelation - of implicit POSIX threads as well. - -2003-09-02 Ross Johnson - - * pthread_win32_attach_detach_np.c (pthread_win32_thread_detach_np): - Add comment. - - * pthread_exit.c (pthread_exit): Fix to recycle the POSIX thread handle in - addition to calling user TSD destructors. Move the implicit POSIX thread exit - handling to ptw32_throw to centralise the logic. - - * ptw32_throw.c (ptw32_throw): Implicit POSIX threads have no point - to jump or throw to, so cleanup and exit the thread here in this case. For - processes using the C runtime, the exit code will be set to the POSIX - reason for the throw (i.e. PTHREAD_CANCEL or the value given to pthread_exit). - Note that pthread_exit() already had similar logic, which has been moved to - here. - - * ptw32_threadDestroy.c (ptw32_threadDestroy): Don't close the Win32 handle - of implicit POSIX threads - expect this to be done by Win32? - -2003-09-01 Ross Johnson - - * pthread_self.c (pthread_self): The newly aquired pthread_t must be - assigned to the reuse stack, not freed, if the routine fails somehow. - -2003-08-13 Ross Johnson - - * pthread_getschedparam.c (pthread_getschedparam): An invalid thread ID - parameter was returning an incorrect error value; now uses a more exhaustive - check for validity. - - * pthread_setschedparam.c (pthread_setschedparam): Likewise. - - * pthread_join.c (pthread_join): Now uses a more exhaustive - check for validity. - - * pthread_detach.c (pthread_detach): Likewise. - - * pthread_cancel.c (pthread_cancel): Likewise. - - * ptw32_threadDestroy.c (ptw32_threadDestroy): pthread_t structs are - never freed - push them onto a stack for reuse. - - * ptw32_new.c (ptw32_new): Check for reusable pthread_t before dynamically - allocating new memory for the struct. - - * pthread_kill.c (pthread_kill): New file; new routine; takes only a zero - signal arg so that applications can check the thread arg for validity; checks - that the underlying Win32 thread HANDLE is valid. - - * pthread.h (pthread_kill): Add prototype. - - * ptw32_reuse.c (ptw32_threadReusePop): New file; new routine; pop a - pthread_t off the reuse stack. pthread_t_ structs that have been destroyed, i.e. - have exited detached or have been joined, are cleaned up and put onto a reuse - stack. Consequently, thread IDs are no longer freed once calloced. The library - will attempt to get a struct off this stack before asking the system to alloc - new memory when creating threads. The stack is guarded by a global mutex. - (ptw32_threadReusePush): New routine; push a pthread_t onto the reuse stack. - - * implement.h (ptw32_threadReusePush): Add new prototype. - (ptw32_threadReusePop): Likewise. - (pthread_t): Add new element. - - * ptw32_processTerminate.c (ptw32_processTerminate): Delete the thread - reuse lock; free all thread ID structs on the thread reuse stack. - - * ptw32_processInitialize.c (ptw32_processInitialize): Initialise the - thread reuse lock. - -2003-07-19 Ross Johnson - - * GNUmakefile: modified to work under MsysDTK environment. - * pthread_spin_lock.c (pthread_spin_lock): Check for NULL arg. - * pthread_spin_unlock.c (pthread_spin_unlock): Likewise. - * pthread_spin_trylock.c (pthread_spin_trylock): Likewise; - fix incorrect pointer value if lock is dynamically initialised by - this function. - * sem_init.c (sem_init): Initialise sem_t value to quell compiler warning. - * sem_destroy.c (sem_destroy): Likewise. - * ptw32_threadStart.c (non-MSVC code sections): Include rather - than old-style ; fix all std:: namespace entities such as - std::terminate_handler instances and associated methods. - * ptw32_callUserDestroyRoutines.c (non-MSVC code sections): Likewise. - -2003-06-24 Piet van Bruggen - - * pthread_spin_destroy.c (pthread_spin_destroy): Was not freeing the - spinlock struct. - -2003-06-22 Nicolas Barry - - * pthread_mutex_destroy.c (pthread_mutex_destroy): When called - with a recursive mutex that was locked by the current thread, the - function was failing with a success return code. - -2003-05-15 Steven Reddie - - * pthread_win32_attach_detach_np.c (pthread_win32_process_detach_np): - NULLify ptw32_selfThreadKey after the thread is destroyed, otherwise - destructors calling pthreads routines might resurrect it again, creating - memory leaks. Call the underlying Win32 Tls routine directly rather than - pthread_setspecific(). - (pthread_win32_thread_detach_np): Likewise. - -2003-05-14 Viv - - * pthread.dsp: Change /MT compile flag to /MD. - -2003-03-04 Alexander Terekhov - - * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Fix failure to - set ownership of mutex on second grab after abstime timeout. - - bug reported by Robert Strycek - -2002-12-17 Thomas Pfaff - - * pthread_mutex_lock.c (ptw32_semwait): New static routine to provide - a non-cancelable sem_wait() function. This is consistent with the - way that pthread_mutex_timedlock.c does it. - (pthread_mutex_lock): Use ptw32_semwait() instead of sem_wait(). - -2002-12-11 Thomas Pfaff - - * pthread_mutex_trylock.c: Should return EBUSY rather than EDEADLK. - * pthread_mutex_destroy.c: Remove redundant ownership test (the - trylock call does this for us); do not destroy a recursively locked - mutex. - -2002-09-20 Michael Johnson - - * pthread_cond_destroy.c (pthread_cond_destroy): - When two different threads exist, and one is attempting to - destroy a condition variable while the other is attempting to - initialize a condition variable that was created with - PTHREAD_COND_INITIALIZER, a deadlock can occur. Shrink - the ptw32_cond_list_lock critical section to fix it. - -2002-07-31 Ross Johnson - - * ptw32_threadStart.c (ptw32_threadStart): Thread cancelLock - destruction moved to ptw32_threadDestroy(). - - * ptw32_threadDestroy.c (ptw32_threadDestroy): Destroy - the thread's cancelLock. Moved here from ptw32_threadStart.c - to cleanup implicit threads as well. - -2002-07-30 Alexander Terekhov - - * pthread_cond_wait.c (ptw32_cond_wait_cleanup): - Remove code designed to avoid/prevent spurious wakeup - problems. It is believed that the sem_timedwait() call - is consuming a CV signal that it shouldn't and this is - breaking the avoidance logic. - -2002-07-30 Ross Johnson - - * sem_timedwait.c (sem_timedwait): Tighten checks for - unreasonable abstime values - that would result in - unexpected timeout values. - - * w32_CancelableWait.c (ptw32_cancelable_wait): - Tighten up return value checking and add comments. - - -2002-06-08 Ross Johnson - - * sem_getvalue.c (sem_getvalue): Now returns a value for the - NEED_SEM version (i.e. earlier versions of WinCE). - - -2002-06-04 Rob Fanner - - * sem_getvalue.c (sem_getvalue): The Johnson M. Hart - approach didn't work - we are forced to take an - intrusive approach. We try to decrement the sema - and then immediately release it again to get the - value. There is a small probability that this may - block other threads, but only momentarily. - -2002-06-03 Ross Johnson - - * sem_init.c (sem_init): Initialise Win32 semaphores - to _POSIX_SEM_VALUE_MAX (which this implementation - defines in pthread.h) so that sem_getvalue() can use - the trick described in the comments in sem_getvalue(). - * pthread.h (_POSIX_SEM_VALUE_MAX): Defined. - (_POSIX_SEM_NSEMS_MAX): Defined - not used but may be - useful for source code portability. - -2002-06-03 Rob Fanner - - * sem_getvalue.c (sem_getvalue): Did not work on NT. - Use approach suggested by Johnson M. Hart in his book - "Win32 System Programming". - -2002-02-28 Ross Johnson - - * errno.c: Compiler directive was incorrectly including code. - * pthread.h: Conditionally added some #defines from config.h - needed when not building the library. e.g. NEED_ERRNO, NEED_SEM. - (PTW32_DLLPORT): Now only defined if _DLL defined. - (_errno): Compiler directive was incorrectly including prototype. - * sched.h: Conditionally added some #defines from config.h - needed when not building the library. - * semaphore.h: Replace an instance of NEED_SEM that should - have been NEED_ERRNO. This change currently has nil effect. - - * GNUmakefile: Correct some recent changes. - - * Makefile: Add rule to generate pre-processor output. - -2002-02-23 Ross Johnson - - * pthread_rwlock_timedrdlock.c: New - untested. - * pthread_rwlock_timedwrlock.c: New - untested. - - * Testsuite passed (except known MSVC++ problems) - - * pthread_cond_destroy.c: Expand the time change - critical section to solve deadlock problem. - - * pthread.c: Add all remaining C modules. - * pthread.h: Use dllexport/dllimport attributes on functions - to avoid using pthread.def. - * sched.h: Likewise. - * semaphore.h: Likewise. - * GNUmakefile: Add new targets for single translation - unit build to maximise inlining potential; generate - pthread.def automatically. - * Makefile: Likewise, but no longer uses pthread.def. - -2002-02-20 Ross Johnson - - * pthread_cond_destroy.c (pthread_cond_destroy): - Enter the time change critical section earlier. - -2002-02-17 Ross Johnson - - * nonportable.c (pthread_delay_np): Make a true - cancelation point. Deferred cancels will interrupt the - wait. - -2002-02-07 Ross Johnson - - Reduced name space pollution. - ----------------------------- - When the appropriate symbols are defined, the headers - will restrict the definitions of new names. In particular, - it must be possible to NOT include the - header and related definitions with some combination - of symbol definitions. Secondly, it should be possible - that additional definitions should be limited to POSIX - compliant symbols by the definition of appropriate symbols. - - * pthread.h: POSIX conditionals. - * sched.h: POSIX conditionals. - * semaphore.h: POSIX conditionals. - - * semaphore.c: Included . - (sem_init): Changed magic 0x7FFFFFFFL to INT_MAX. - (sem_getvalue): Trial version. - - Reduce executable size. - ----------------------- - When linking with the static library, only those - routines actually called, either directly or indirectly - should be included. - - [Gcc has the -ffunction-segments option to do this but MSVC - doesn't have this feature as far as I can determine. Other - compilers are undetermined as well. - rpj] - - * semaphore.c: All routines are now in separate compilation units; - This file is used to congregate the separate modules for - potential inline optimisation and backward build compatibility. - * sem_close.c: Separated routine from semaphore.c. - * ptw32_decrease_semaphore.c: Likewise. - * sem_destroy.c: Likewise. - * sem_getvalue.c: Likewise. - * ptw32_increase_semaphore.c: Likewise. - * sem_init.c: Likewise. - * sem_open.c: Likewise. - * sem_post.c: Likewise. - * sem_post_multiple.c: Likewise. - * sem_timedwait.c: Likewise. - * sem_trywait.c: Likewise. - * sem_unlink.c: Likewise. - * sem_wait.c: Likewise. - -2002-02-04 Ross Johnson - - The following extends the idea above to the rest of pthreads-win32 - rpj - - * attr.c: All routines are now in separate compilation units; - This file is used to congregate the separate modules for - potential inline optimisation and backward build compatibility. - * pthread_attr_destroy.c: Separated routine from attr.c. - * pthread_attr_getdetachstate.c: Likewise. - * pthread_attr_getscope.c: Likewise. - * pthread_attr_getstackaddr.c: Likewise. - * pthread_attr_getstacksize.c: Likewise. - * pthread_attr_init.c: Likewise. - * pthread_attr_is_attr.c: Likewise. - * pthread_attr_setdetachstate.c: Likewise. - * pthread_attr_setscope.c: Likewise. - * pthread_attr_setstackaddr.c: Likewise. - * pthread_attr_setstacksize.c: Likewise. - - * pthread.c: Agregation of agregate modules for super-inlineability. - -2002-02-02 Ross Johnson - - * cancel.c: Rearranged some code and introduced checks - to disable cancelation at the start of a thread's cancelation - run to prevent double cancelation. The main problem - arises if a thread is canceling and then receives a subsequent - async cancel request. - * private.c: Likewise. - * condvar.c: Place pragmas around cleanup_push/pop to turn - off inline optimisation (/Obn where n>0 - MSVC only). Various - optimisation switches in MSVC turn this on, which interferes with - the way that cleanup handlers are run in C++ EH and SEH - code. Application code compiled with inline optimisation must - also wrap cleanup_push/pop blocks with the pragmas, e.g. - #pragma inline_depth(0) - pthread_cleanup_push(...) - ... - pthread_cleanup_pop(...) - #pragma inline_depth(8) - * rwlock.c: Likewise. - * mutex.c: Remove attempts to inline some functions. - * signal.c: Modify misleading comment. - -2002-02-01 Ross Johnson - - * semaphore.c (sem_trywait): Fix missing errno return - for systems that define NEED_SEM (e.g. early WinCE). - * mutex.c (pthread_mutex_timedlock): Return ENOTSUP - for systems that define NEED_SEM since they don't - have sem_trywait(). - -2002-01-27 Ross Johnson - - * mutex.c (pthread_mutex_timedlock): New function suggested by - Alexander Terekhov. The logic required to implement this - properly came from Alexander, with some collaboration - with Thomas Pfaff. - (pthread_mutex_unlock): Wrap the waiters check and sema - post in a critical section to prevent a race with - pthread_mutex_timedlock. - (ptw32_timed_semwait): New function; - returns a special result if the absolute timeout parameter - represents a time already passed when called; used by - pthread_mutex_timedwait(). Have deliberately not reused - the name "ptw32_sem_timedwait" because they are not the same - routine. - * condvar.c (ptw32_cond_timedwait): Use the new sem_timedwait() - instead of ptw32_sem_timedwait(), which now has a different - function. See previous. - * implement.h: Remove prototype for ptw32_sem_timedwait. - See next. - (pthread_mutex_t_): Add critical section element for access - to lock_idx during mutex post-timeout processing. - * semaphore.h (sem_timedwait): See next. - * semaphore.c (sem_timedwait): See next. - * private.c (ptw32_sem_timedwait): Move to semaphore.c - and rename as sem_timedwait(). - -2002-01-18 Ross Johnson - - * sync.c (pthread_join): Was getting the exit code from the - calling thread rather than the joined thread if - defined(__MINGW32__) && !defined(__MSVCRT__). - -2002-01-15 Ross Johnson - - * pthread.h: Unless the build explicitly defines __CLEANUP_SEH, - __CLEANUP_CXX, or __CLEANUP_C, then the build defaults to - __CLEANUP_C style cleanup. This style uses setjmp/longjmp - in the cancelation and thread exit implementations and therefore - won't do stack unwinding if linked to applications that have it - (e.g. C++ apps). This is currently consistent with most/all - commercial Unix POSIX threads implementations. - - * spin.c (pthread_spin_init): Edit renamed function call. - * nonportable.c (pthread_num_processors_np): New. - (pthread_getprocessors_np): Renamed to ptw32_getprocessors - and moved to private.c. - * private.c (pthread_getprocessors): Moved here from - nonportable.c. - * pthread.def (pthread_getprocessors_np): Removed - from export list. - - * rwlock.c (pthread_rwlockattr_init): New. - (pthread_rwlockattr_destroy): New. - (pthread_rwlockattr_getpshared): New. - (pthread_rwlockattr_setpshared): New. - -2002-01-14 Ross Johnson - - * attr.c (pthread_attr_setscope): Fix struct pointer - indirection error introduced 2002-01-04. - (pthread_attr_getscope): Likewise. - -2002-01-12 Ross Johnson - - * pthread.dsp (SOURCE): Add missing source files. - -2002-01-08 Ross Johnson - - * mutex.c (pthread_mutex_trylock): use - ptw32_interlocked_compare_exchange function pointer - rather than ptw32_InterlockedCompareExchange() directly - to retain portability to non-iX86 processors, - e.g. WinCE etc. The pointer will point to the native - OS version of InterlockedCompareExchange() if the - OS supports it (see ChangeLog entry of 2001-10-17). - -2002-01-07 Thomas Pfaff , Alexander Terekhov - - * mutex.c (pthread_mutex_init): Remove critical - section calls. - (pthread_mutex_destroy): Likewise. - (pthread_mutex_unlock): Likewise. - (pthread_mutex_trylock): Likewise; uses - ptw32_InterlockedCompareExchange() to avoid need for - critical section; library is no longer i386 compatible; - recursive mutexes now increment the lock count rather - than return EBUSY; errorcheck mutexes return EDEADLCK - rather than EBUSY. This behaviour is consistent with the - Solaris pthreads implementation. - * implement.h (pthread_mutex_t_): Remove critical - section element - no longer needed. - - -2002-01-04 Ross Johnson - - * attr.c (pthread_attr_setscope): Add more error - checking and actually store the scope value even - though it's not really necessary. - (pthread_attr_getscope): Return stored value. - * implement.h (pthread_attr_t_): Add new scope element. - * ANNOUNCE: Fix out of date comment next to - pthread_attr_setscope in conformance section. - -2001-12-21 Alexander Terekhov - - * mutex.c (pthread_mutex_lock): Decrementing lock_idx was - not thread-safe. - (pthread_mutex_trylock): Likewise. - -2001-10-26 prionx@juno.com - - * semaphore.c (sem_init): Fix typo and missing bracket - in conditionally compiled code. Only older versions of - WinCE require this code, hence it doesn't normally get - tested; somehow when sem_t reverted to an opaque struct - the calloc NULL check was left in the conditionally included - section. - (sem_destroy): Likewise, the calloced sem_t wasn't being freed. - -2001-10-25 Ross Johnson - - * GNUmakefile (libwsock32): Add to linker flags for - WSAGetLastError() and WSASetLastError(). - * Makefile (wsock32.lib): Likewise. - * create.c: Minor mostly inert changes. - * implement.h (PTW32_MAX): Move into here and renamed - from sched.h. - (PTW32_MIN): Likewise. - * GNUmakefile (TEST_ICE): Define if testing internal - implementation of InterlockedCompareExchange. - * Makefile (TEST_ICE): Likewise. - * private.c (TEST_ICE): Likewise. - -2001-10-24 Ross Johnson - - * attr.c (pthread_attr_setstacksize): Quell warning - from LCC by conditionally compiling the stacksize - validity check. LCC correctly warns that the condition - (stacksize < PTHREAD_STACK_MIN) is suspicious - because STACK_MIN is 0 and stacksize is of type - size_t (or unsigned int). - -2001-10-17 Ross Johnson - - * barrier.c: Move _LONG and _LPLONG defines into - implement.h; rename to PTW32_INTERLOCKED_LONG and - PTW32_INTERLOCKED_LPLONG respectively. - * spin.c: Likewise; ptw32_interlocked_compare_exchange used - in place of InterlockedCompareExchange directly. - * global.c (ptw32_interlocked_compare_exchange): Add - prototype for this new routine pointer to be used when - InterlockedCompareExchange isn't supported by Windows. - * nonportable.c (pthread_win32_process_attach_np): Check for - support of InterlockedCompareExchange in kernel32 and assign its - address to ptw32_interlocked_compare_exchange if it exists, or - our own ix86 specific implementation ptw32_InterlockedCompareExchange. - *private.c (ptw32_InterlockedCompareExchange): An - implementation of InterlockedCompareExchange() which is - specific to ix86; written directly in assembler for either - MSVC or GNU C; needed because Windows 95 doesn't support - InterlockedCompareExchange(). - - * sched.c (sched_get_priority_min): Extend to return - THREAD_PRIORITY_IDLE. - (sched_get_priority_max): Extend to return - THREAD_PRIORITY_CRITICAL. - -2001-10-15 Ross Johnson - - * spin.c (pthread_spin_lock): PTHREAD_SPINLOCK_INITIALIZER - was causing a program fault. - (pthread_spin_init): Could have alloced memory - without freeing under some error conditions. - - * mutex.c (pthread_mutex_init): Move memory - allocation of mutex struct after checking for - PROCESS_SHARED. - -2001-10-12 Ross Johnson - - * spin.c (pthread_spin_unlock): Was not returning - EPERM if the spinlock was not locked, for multi CPU - machines. - -2001-10-08 Ross Johnson - - * spin.c (pthread_spin_trylock): Was not returning - EBUSY for multi CPU machines. - -2001-08-24 Ross Johnson - - * condvar.c (pthread_cond_destroy): Remove cv element - that is no longer used. - * implement.h: Likewise. - -2001-08-23 Alexander Terekhov - - * condvar.c (pthread_cond_destroy): fix bug with - respect to deadlock in the case of concurrent - _destroy/_unblock; a condition variable can be destroyed - immediately after all the threads that are blocked on - it are awakened. - -2001-08-23 Phil Frisbie, Jr. - - * tsd.c (pthread_getspecific): Preserve the last - winsock error [from WSAGetLastError()]. - -2001-07-18 Scott McCaskill - - * mutex.c (pthread_mutexattr_init): Return ENOMEM - immediately and don't dereference the NULL pointer - if calloc fails. - (pthread_mutexattr_getpshared): Don't dereference - a pointer that is possibly NULL. - * barrier.c (pthread_barrierattr_init): Likewise - (pthread_barrierattr_getpshared): Don't dereference - a pointer that is possibly NULL. - * condvar.c (pthread_condattr_getpshared): Don't dereference - a pointer that is possibly NULL. - -2001-07-15 Ross Johnson - - * rwlock.c (pthread_rwlock_wrlock): Is allowed to be - a cancelation point; re-enable deferred cancelability - around the CV call. - -2001-07-10 Ross Johnson - - * barrier.c: Still more revamping. The exclusive access - mutex isn't really needed so it has been removed and replaced - by an InterlockedDecrement(). nSerial has been removed. - iStep is now dual-purpose. The process shared attribute - is now stored in the barrier struct. - * implement.h (pthread_barrier_t_): Lost some/gained one - elements. - * private.c (ptw32_threadStart): Removed some comments. - -2001-07-10 Ross Johnson - - * barrier.c: Revamped to fix the race condition. Two alternating - semaphores are used instead of the PulseEvent. Also improved - overall throughput by returning PTHREAD_BARRIER_SERIAL_THREAD - to the first waking thread. - * implement.h (pthread_barrier_t_): Revamped. - -2001-07-09 Ross Johnson - - * barrier.c: Fix several bugs in all routines. Now passes - tests/barrier5.c which is fairly rigorous. There is still - a non-optimal work-around for a race condition between - the barrier breeched event signal and event wait. Basically - the last (signalling) thread to hit the barrier yields - to allow any other threads, which may have lost the race, - to complete. - -2001-07-07 Ross Johnson - - * barrier.c: Changed synchronisation mechanism to a - Win32 manual reset Event and use PulseEvent to signal - waiting threads. If the implementation continued to use - a semaphore it would require a second semaphore and - some management to use them alternately as barriers. A - single semaphore allows threads to cascade from one barrier - through the next, leaving some threads blocked at the first. - * implement.h (pthread_barrier_t_): As per above. - * general: Made a number of other routines inlinable. - -2001-07-07 Ross Johnson - - * spin.c: Revamped and working; included static initialiser. - Now beta level. - * barrier.c: Likewise. - * condvar.c: Macro constant change; inline auto init routine. - * mutex.c: Likewise. - * rwlock.c: Likewise. - * private.c: Add support for spinlock initialiser. - * global.c: Likewise. - * implement.h: Likewise. - * pthread.h (PTHREAD_SPINLOCK_INITIALIZER): Fix typo. - -2001-07-05 Ross Johnson - - * barrier.c: Remove static initialisation - irrelevent - for this object. - * pthread.h (PTHREAD_BARRIER_INITIALIZER): Removed. - * rwlock.c (pthread_rwlock_wrlock): This routine is - not a cancelation point - disable deferred - cancelation around call to pthread_cond_wait(). - -2001-07-05 Ross Johnson - - * spin.c: New module implementing spin locks. - * barrier.c: New module implementing barriers. - * pthread.h (_POSIX_SPIN_LOCKS): defined. - (_POSIX_BARRIERS): Defined. - (pthread_spin_*): Defined. - (pthread_barrier*): Defined. - (PTHREAD_BARRIER_SERIAL_THREAD): Defined. - * implement.h (pthread_spinlock_t_): Defined. - (pthread_barrier_t_): Defined. - (pthread_barrierattr_t_): Defined. - - * mutex.c (pthread_mutex_lock): Return with the error - if an auto-initialiser initialisation fails. - - * nonportable.c (pthread_getprocessors_np): New; gets the - number of available processors for the current process. - -2001-07-03 Ross Johnson - - * pthread.h (_POSIX_READER_WRITER_LOCKS): Define it - if not already defined. - -2001-07-01 Alexander Terekhov - - * condvar.c: Fixed lost signal bug reported by Timur Aydin - (taydin@snet.net). - [RPJ (me) didn't translate the original algorithm - correctly.] - * semaphore.c: Added sem_post_multiple; this is a useful - routine, but it doesn't appear to be standard. For now it's - not an exported function. - -2001-06-25 Ross Johnson - - * create.c (pthread_create): Add priority inheritance - attributes. - * mutex.c (pthread_mutex_lock): Remove some overhead for - PTHREAD_MUTEX_NORMAL mutex types. Specifically, avoid - calling pthread_self() and pthread_equal() to check/set - the mutex owner. Introduce a new pseudo owner for this - type. Test results suggest increases in speed of up to - 90% for non-blocking locks. - This is the default type of mutex used internally by other - synchronising objects, ie. condition variables and - read-write locks. The test rwlock7.c shows about a - 30-35% speed increase over snapshot 2001-06-06. The - price of this is that the application developer - must ensure correct behaviour, or explicitly set the - mutex to a safer type such as PTHREAD_MUTEX_ERRORCHECK. - For example, PTHREAD_MUTEX_NORMAL (or PTHREAD_MUTEX_DEFAULT) - type mutexes will not return an error if a thread which is not - the owner calls pthread_mutex_unlock. The call will succeed - in unlocking the mutex if it is currently locked, but a - subsequent unlock by the true owner will then fail with EPERM. - This is however consistent with some other implementations. - (pthread_mutex_unlock): Likewise. - (pthread_mutex_trylock): Likewise. - (pthread_mutex_destroy): Likewise. - * attr.c (pthread_attr_init): PTHREAD_EXPLICIT_SCHED is the - default inheritance attribute; THREAD_PRIORITY_NORMAL is - the default priority for new threads. - * sched.c (pthread_attr_setschedpolicy): Added routine. - (pthread_attr_getschedpolicy): Added routine. - (pthread_attr_setinheritsched): Added routine. - (pthread_attr_getinheritsched): Added routine. - * pthread.h (sched_rr_set_interval): Added as a macro; - returns -1 with errno set to ENOSYS. - -2001-06-23 Ross Johnson - - *sched.c (pthread_attr_setschedparam): Add priority range - check. - (sched_setscheduler): New function; checks for a valid - pid and policy; checks for permission to set information - in the target process; expects pid to be a Win32 process ID, - not a process handle; the only scheduler policy allowed is - SCHED_OTHER. - (sched_getscheduler): Likewise, but checks for permission - to query. - * pthread.h (SCHED_*): Moved to sched.h as defined in the - POSIX standard. - * sched.h (SCHED_*): Moved from pthread.h. - (pid_t): Defined if necessary. - (sched_setscheduler): Defined. - (sched_getscheduler): Defined. - * pthread.def (sched_setscheduler): Exported. - (sched_getscheduler): Likewise. - -2001-06-23 Ralf Brese - - * create.c (pthread_create): Set thread priority from - thread attributes. - -2001-06-18 Ross Johnson - - * Made organisational-only changes to UWIN additions. - * dll.c (dllMain): Moved UWIN process attach code - to pthread_win32_process_attach_np(); moved - instance of pthread_count to global.c. - * global.c (pthread_count): Moved from dll.c. - * nonportable.c (pthread_win32_process_attach_np): - Moved _UWIN code to here from dll.c. - * implement.h (pthread_count): Define extern int. - * create.c (pthread_count): Remove extern int. - * private.c (pthread_count): Likewise. - * exit.c (pthread_count): Likewise. - -2001-06-18 David Korn - - * dll.c: Added changes necessary to work with UWIN. - * create.c: Likewise. - * pthread.h: Likewise. - * misc.c: Likewise. - * exit.c: Likewise. - * private.c: Likewise. - * implement.h: Likewise. - There is some room at the start of struct pthread_t_ - to implement the signal semantics in UWIN's posix.dll - although this is not yet complete. - * Nmakefile: Compatible with UWIN's Nmake utility. - * Nmakefile.tests: Likewise - for running the tests. - -2001-06-08 Ross Johnson - - * semaphore.h (sem_t): Fixed for compile and test. - * implement.h (sem_t_): Likewise. - * semaphore.c: Likewise. - * private.c (ptw32_sem_timedwait): Updated to use new - opaque sem_t. - -2001-06-06 Ross Johnson - - * semaphore.h (sem_t): Is now an opaque pointer; - moved actual definition to implement.h. - * implement.h (sem_t_): Move here from semaphore.h; - was the definition of sem_t. - * semaphore.c: Wherever necessary, changed use of sem - from that of a pointer to a pointer-pointer; added - extra checks for a valid sem_t; NULL sem_t when - it is destroyed; added extra checks when creating - and destroying sem_t elements in the NEED_SEM - code branches; changed from using a pthread_mutex_t - ((*sem)->mutex) to CRITICAL_SECTION ((*sem)->sem_lock_cs) - in NEED_SEM branches for access serialisation. - -2001-06-06 Ross Johnson - - * mutex.c (pthread_mutexattr_init): Remove - ptw32_mutex_default_kind. - -2001-06-05 Ross Johnson - - * nonportable.c (pthread_mutex_setdefaultkind_np): - Remove - should not have been included in the first place. - (pthread_mutex_getdefaultkind_np): Likewise. - * global.c (ptw32_mutex_default_kind): Likewise. - * mutex.c (pthread_mutex_init): Remove use of - ptw32_mutex_default_kind. - * pthread.h (pthread_mutex_setdefaultkind_np): Likewise. - (pthread_mutex_getdefaultkind_np): Likewise. - * pthread.def (pthread_mutexattr_setkind_np): Added. - (pthread_mutexattr_getkind_np): Likewise. - - * README: Many changes that should have gone in before - the last snapshot. - * README.NONPORTABLE: New - referred to by ANNOUNCE - but never created; documents the non-portable routines - included in the library - moved from README with new - routines added. - * ANNOUNCE (pthread_mutexattr_setkind_np): Added to - compliance list. - (pthread_mutexattr_getkind_np): Likewise. - -2001-06-04 Ross Johnson - - * condvar.c: Add original description of the algorithm as - developed by Terekhov and Thomas, plus reference to - README.CV. - -2001-06-03 Alexander Terekhov , Louis Thomas - - * condvar.c (pthread_cond_init): Completely revamped. - (pthread_cond_destroy): Likewise. - (ptw32_cond_wait_cleanup): Likewise. - (ptw32_cond_timedwait): Likewise. - (ptw32_cond_unblock): New general signaling routine. - (pthread_cond_signal): Now calls ptw32_cond_unblock. - (pthread_cond_broadcast): Likewise. - * implement.h (pthread_cond_t_): Revamped. - * README.CV: New; explanation of the above changes. - -2001-05-30 Ross Johnson - - * pthread.h (rand_r): Fake using _seed argument to quell - compiler warning (compiler should optimise this away later). - - * GNUmakefile (OPT): Leave symbolic information out of the library - and increase optimisation level - for smaller faster prebuilt - dlls. - -2001-05-29 Milan Gardian - - * Makefile: fix typo. - * pthreads.h: Fix problems with stdcall/cdecl conventions, in particular - remove the need for PT_STDCALL everywhere; remove warning supression. - * (errno): Fix the longstanding "inconsistent dll linkage" problem - with errno; now also works with /MD debugging libs - - warnings emerged when compiling pthreads library with /MD (or /MDd) - compiler switch, instead of /MT (or /MTd) (i.e. when compiling pthreads - using Multithreaded DLL CRT instead of Multithreaded statically linked - CRT). - * create.c (pthread_create): Likewise; fix typo. - * private.c (ptw32_threadStart): Eliminate use of terminate() which doesn't - throw exceptions. - * Remove unnecessary #includes from a number of modules - - [I had to #include malloc.h in implement.h for gcc - rpj]. - -2001-05-29 Thomas Pfaff - - * pthread.h (PTHREAD_MUTEX_DEFAULT): New; equivalent to - PTHREAD_MUTEX_DEFAULT_NP. - * (PTHREAD_MUTEX_NORMAL): Similarly. - * (PTHREAD_MUTEX_ERRORCHECK): Similarly. - * (PTHREAD_MUTEX_RECURSIVE): Similarly. - * (pthread_mutex_setdefaultkind_np): New; Linux compatibility stub - for pthread_mutexattr_settype. - * (pthread_mutexattr_getkind_np): New; Linux compatibility stub - for pthread_mutexattr_gettype. - * mutex.c (pthread_mutexattr_settype): New; allow - the following types of mutex: - PTHREAD_MUTEX_DEFAULT_NP - PTHREAD_MUTEX_NORMAL_NP - PTHREAD_MUTEX_ERRORCHECK_NP - PTHREAD_MUTEX_RECURSIVE_NP - * Note that PTHREAD_MUTEX_DEFAULT is equivalent to - PTHREAD_MUTEX_NORMAL - ie. mutexes should no longer - be recursive by default, and a thread will deadlock if it - tries to relock a mutex it already owns. This is inline with - other pthreads implementations. - * (pthread_mutex_lock): Process the lock request - according to the mutex type. - * (pthread_mutex_init): Eliminate use of Win32 mutexes as the - basis of POSIX mutexes - instead, a combination of one critical section - and one semaphore are used in conjunction with Win32 Interlocked* routines. - * (pthread_mutex_destroy): Likewise. - * (pthread_mutex_lock): Likewise. - * (pthread_mutex_trylock): Likewise. - * (pthread_mutex_unlock): Likewise. - * Use longjmp/setjmp to implement cancelation when building the library - using a C compiler which doesn't support exceptions, e.g. gcc -x c (note - that gcc -x c++ uses exceptions). - * Also fixed some of the same typos and eliminated PT_STDCALL as - Milan Gardian's patches above. - -2001-02-07 Alexander Terekhov - - * rwlock.c: Revamped. - * implement.h (pthread_rwlock_t_): Redefined. - This implementation does not have reader/writer starvation problem. - Rwlock attempts to behave more like a normal mutex with - races and scheduling policy determining who is more important; - It also supports recursive locking, - has less synchronization overhead (no broadcasts at all, - readers are not blocked on any condition variable) and seem to - be faster than the current implementation [W98 appears to be - approximately 15 percent faster at least - on top of speed increase - from Thomas Pfaff's changes to mutex.c - rpj]. - -2000-12-29 Ross Johnson - - * Makefile: Back-out "for" loops which don't work. - - * GNUmakefile: Remove the fake.a target; add the "realclean" - target; don't remove built libs under the "clean" target. - - * config.h: Add a guard against multiple inclusion. - - * semaphore.h: Add some defines from config.h to make - semaphore.h independent of config.h when building apps. - - * pthread.h (_errno): Back-out previous fix until we know how to - fix it properly. - - * implement.h (lockCount): Add missing element to pthread_mutex_t_. - - * sync.c (pthread_join): Spelling fix in comment. - - * private.c (ptw32_threadStart): Reset original termination - function (C++). - (ptw32_threadStart): Cleanup detached threads early in case - the library is statically linked. - (ptw32_callUserDestroyRoutines): Remove [SEH] __try block from - destructor call so that unhandled exceptions will be passed through - to the system; call terminate() from [C++] try block for the same - reason. - - * tsd.c (pthread_getspecific): Add comment. - - * mutex.c (pthread_mutex_init): Initialise new elements in - pthread_mutex_t. - (pthread_mutex_unlock): Invert "pthread_equal()" test. - -2000-12-28 Ross Johnson - - * semaphore.c (mode_t): Use ifndef HAVE_MODE_T to include definition. - - * config.h.in (HAVE_MODE_T): Added. - (_UWIN): Start adding defines for the UWIN package. - - * private.c (ptw32_threadStart): Unhandled exceptions are - now passed through to the system to deal with. This is consistent - with normal Windows behaviour. C++ applications may use - set_terminate() to override the default behaviour which is - to call ptw32_terminate(). Ptw32_terminate() cleans up some - POSIX thread stuff before calling the system default function - which calls abort(). The users termination function should conform - to standard C++ semantics which is to not return. It should - exit the thread (call pthread_exit()) or exit the application. - * private.c (ptw32_terminate): Added as the default set_terminate() - function. It calls the system default function after cleaning up - some POSIX thread stuff. - - * implement.h (ptw32_try_enter_critical_section): Move - declaration. - * global.c (ptw32_try_enter_critical_section): Moved - from dll.c. - * dll.c: Move process and thread attach/detach code into - functions in nonportable.c. - * nonportable.c (pthread_win32_process_attach_np): Process - attach code from dll.c is now available to static linked - applications. - * nonportable.c (pthread_win32_process_detach_np): Likewise. - * nonportable.c (pthread_win32_thread_attach_np): Likewise. - * nonportable.c (pthread_win32_thread_detach_np): Likewise. - - * pthread.h: Add new non-portable prototypes for static - linked applications. - - * GNUmakefile (OPT): Increase optimisation flag and remove - debug info flag. - - * pthread.def: Add new non-portable exports for static - linked applications. - -2000-12-11 Ross Johnson - - * FAQ: Update Answer 6 re getting a fully working - Mingw32 built library. - -2000-10-10 Steven Reddie - - * misc.c (pthread_self): Restore Win32 "last error" - cleared by TlsGetValue() call in - pthread_getspecific() - -2000-09-20 Arthur Kantor - - * mutex.c (pthread_mutex_lock): Record the owner - of the mutex. This requires also keeping count of - recursive locks ourselves rather than leaving it - to Win32 since we need to know when to NULL the - thread owner when the mutex is unlocked. - (pthread_mutex_trylock): Likewise. - (pthread_mutex_unlock): Check that the calling - thread owns the mutex, decrement the recursive - lock count, and NULL the owner if zero. Return - EPERM if the mutex is owned by another thread. - * implement.h (pthread_mutex_t_): Add ownerThread - and lockCount members. - -2000-09-13 Jef Gearhart - - * mutex.c (pthread_mutex_init): Call - TryEnterCriticalSection through the pointer - rather than directly so that the dll can load - on Windows versions that can't resolve the - function, eg. Windows 95 - -2000-09-09 Ross Johnson - - * pthread.h (ctime_r): Fix arg. - -2000-09-08 Ross Johnson - - * GNUmakefile(_WIN32_WINNT=0x400): Define in CFLAGS; - doesn't seem to be needed though. - - * cancel.c (pthread_cancel): Must get "self" through - calling pthread_self() which will ensure a POSIX thread - struct is built for non-POSIX threads; return an error - if this fails - - Ollie Leahy - (pthread_setcancelstate): Likewise. - (pthread_setcanceltype): Likewise. - * misc.c (ptw32_cancelable_wait): Likewise. - - * private.c (ptw32_tkAssocCreate): Remove unused #if 0 - wrapped code. - - * pthread.h (ptw32_get_exception_services_code): - Needed to be forward declared unconditionally. - -2000-09-06 Ross Johnson - - * cancel.c (pthread_cancel): If called from the main - thread "self" would be NULL; get "self" via pthread_self() - instead of directly from TLS so that an implicit - pthread object is created. - - * misc.c (pthread_equal): Strengthen test for NULLs. - -2000-09-02 Ross Johnson - - * condvar.c (ptw32_cond_wait_cleanup): Ensure that all - waking threads check if they are the last, and notify - the broadcaster if so - even if an error occurs in the - waiter. - - * semaphore.c (_decrease_semaphore): Should be - a call to ptw32_decrease_semaphore. - (_increase_semaphore): Should be a call to - ptw32_increase_semaphore. - - * misc.c (ptw32_cancelable_wait): Renamed from - CancelableWait. - * rwlock.c (_rwlock_check*): Renamed to - ptw32_rwlock_check*. - * mutex.c (_mutex_check*): Renamed to ptw32_mutex_check*. - * condvar.c (cond_timed*): Renamed to ptw32_cond_timed*. - (_cond_check*): Renamed to ptw32_cond_check*. - (cond_wait_cleanup*): Rename to ptw32_cond_wait_cleanup*. - (ptw32_cond_timedwait): Add comments. - -2000-08-22 Ross Johnson - - * private.c (ptw32_throw): Fix exception test; - move exceptionInformation declaration. - - * tsd.c (pthread_key_create): newkey wrongly declared. - - * pthread.h: Fix comment block. - -2000-08-18 Ross Johnson - - * mutex.c (pthread_mutex_destroy): Check that the mutex isn't - held; invalidate the mutex as early as possible to avoid - contention; not perfect - FIXME! - - * rwlock.c (pthread_rwlock_init): Remove redundant assignment - to "rw". - (pthread_rwlock_destroy): Invalidate the rwlock before - freeing up any of it's resources - to avoid contention. - - * private.c (ptw32_tkAssocCreate): Change assoc->lock - to use a dynamically initialised mutex - only consumes - a W32 mutex or critical section when first used, - not before. - - * mutex.c (pthread_mutex_init): Remove redundant assignment - to "mx". - (pthread_mutexattr_destroy): Set attribute to NULL - before freeing it's memory - to avoid contention. - - * implement.h (PTW32_EPS_CANCEL/PTW32_EPS_EXIT): - Must be defined for all compilers - used as generic - exception selectors by ptw32_throw(). - - * Several: Fix typos from scripted edit session - yesterday. - - * nonportable.c (pthread_mutexattr_setforcecs_np): - Moved this function from mutex.c. - (pthread_getw32threadhandle_np): New function to - return the win32 thread handle that the POSIX - thread is using. - * mutex.c (pthread_mutexattr_setforcecs_np): - Moved to new file "nonportable.c". - - * pthread.h (PTW32_BUILD): Only redefine __except - and catch compiler keywords if we aren't building - the library (ie. PTW32_BUILD is not defined) - - this is safer than defining and then undefining - if not building the library. - * implement.h: Remove __except and catch undefines. - * Makefile (CFLAGS): Define PTW32_BUILD. - * GNUmakefile (CFLAGS): Define PTW32_BUILD. - - * All appropriate: Change Pthread_exception* to - ptw32_exception* to be consistent with internal - identifier naming. - - * private.c (ptw32_throw): New function to provide - a generic exception throw for all internal - exceptions and EH schemes. - (ptw32_threadStart): pthread_exit() value is now - returned via the thread structure exitStatus - element. - * exit.c (pthread_exit): pthread_exit() value is now - returned via the thread structure exitStatus - element. - * cancel.c (ptw32_cancel_self): Now uses ptw32_throw. - (pthread_setcancelstate): Ditto. - (pthread_setcanceltype): Ditto. - (pthread_testcancel): Ditto. - (pthread_cancel): Ditto. - * misc.c (CancelableWait): Ditto. - * exit.c (pthread_exit): Ditto. - * All applicable: Change PTW32_ prefix to - PTW32_ prefix to remove leading underscores - from private library identifiers. - -2000-08-17 Ross Johnson - - * All applicable: Change _pthread_ prefix to - ptw32_ prefix to remove leading underscores - from private library identifiers (single - and double leading underscores are reserved in the - ANSI C standard for compiler implementations). - - * tsd.c (pthread_create_key): Initialise temporary - key before returning it's address to avoid race - conditions. - -2000-08-13 Ross Johnson - - * errno.c: Add _MD precompile condition; thus far - had no effect when using /MD compile option but I - thnk it should be there. - - * exit.c: Add __cplusplus to various #if lines; - was compiling SEH code even when VC++ had - C++ compile options. - - * private.c: ditto. - - * create.c (pthread_create): Add PT_STDCALL macro to - function pointer arg in _beginthread(). - - * pthread.h: PT_STDCALL really does need to be defined - in both this and impliment.h; don't set it to __cdecl - - this macro is only used to extend function pointer - casting for functions that will be passed as parameters. - (~PThreadCleanup): add cast and group expression. - (_errno): Add _MD compile conditional. - (PtW32NoCatchWarn): Change pragma message. - - * implement.h: Move and change PT_STDCALL define. - - * need_errno.h: Add _MD to compilation conditional. - - * GNUmakefile: Substantial rewrite for new naming - convention; set for nil optimisation (turn it up - when we have a working library build; add target - "fake.a" to build a libpthreadw32.a from the VC++ - built DLL pthreadVCE.dll. - - * pthread.def (LIBRARY): Don't specify in the .def - file - it is specified on the linker command line - since we now use the same .def file for variously - named .dlls. - - * Makefile: Substantial rewrite for new naming - convention; default nmake target only issues a - help message; run nmake with specific target - corresponding to the EH scheme being used. - - * README: Update information; add naming convention - explanation. - - * ANNOUNCE: Update information. - -2000-08-12 Ross Johnson - - * pthread.h: Add compile-time message when using - MSC_VER compiler and C++ EH to warn application - programmers to use PtW32Catch instead of catch(...) - if they want cancelation and pthread_exit to work. - - * implement.h: Remove #include ; we - use our own local semaphore.h. - -2000-08-10 Ross Johnson - - * cleanup.c (pthread_pop_cleanup): Remove _pthread - prefix from __except and catch keywords; implement.h - now simply undefines ptw32__except and - ptw32_catch if defined; VC++ was not textually - substituting ptw32_catch etc back to catch as - it was redefined; the reason for using the prefixed - version was to make it clear that it was not using - the pthread.h redefined catch keyword. - - * private.c (ptw32_threadStart): Ditto. - (ptw32_callUserDestroyRoutines): Ditto. - - * implement.h (ptw32__except): Remove #define. - (ptw32_catch): Remove #define. - - * GNUmakefile (pthread.a): New target to build - libpthread32.a from pthread.dll using dlltool. - - * buildlib.bat: Duplicate cl commands with args to - build C++ EH version of pthread.dll; use of .bat - files is redundant now that nmake compatible - Makefile is included; used as a kludge only now. - - * Makefile: Localise some macros and fix up the clean: - target to extend it and work properly. - - * CONTRIBUTORS: Add contributors. - - * ANNOUNCE: Updated. - - * README: Updated. - -2000-08-06 Ross Johnson - - * pthread.h: Remove #warning - VC++ doesn't accept it. - -2000-08-05 Ross Johnson - - * pthread.h (PtW32CatchAll): Add macro. When compiling - applications using VC++ with C++ EH rather than SEH - 'PtW32CatchAll' must be used in place of any 'catch( ... )' - if the application wants pthread cancelation or - pthread_exit() to work. - -2000-08-03 Ross Johnson - - * pthread.h: Add a base class ptw32_exception for - library internal exceptions and change the "catch" - re-define macro to use it. - -2000-08-02 Ross Johnson - - * GNUmakefile (CFLAGS): Add -mthreads. - Add new targets to generate cpp and asm output. - - * sync.c (pthread_join): Remove dead code. - -2000-07-25 Tristan Savatier - - * sched.c (sched_get_priority_max): Handle different WinCE and - Win32 priority values together. - (sched_get_priority_min): Ditto. - -2000-07-25 Ross Johnson - - * create.c (pthread_create): Force new threads to wait until - pthread_create has the new thread's handle; we also retain - a local copy of the handle for internal use until - pthread_create returns. - - * private.c (ptw32_threadStart): Initialise ei[]. - (ptw32_threadStart): When beginthread is used to start the - thread, force waiting until the creator thread had the - thread handle. - - * cancel.c (ptw32_cancel_thread): Include context switch - code for defined(_X86_) environments in addition to _M_IX86. - - * rwlock.c (pthread_rwlock_destroy): Assignment changed - to avoid compiler warning. - - * private.c (ptw32_get_exception_services_code): Cast - NULL return value to avoid compiler warning. - - * cleanup.c (pthread_pop_cleanup): Initialise "cleanup" variable - to avoid compiler warnings. - - * misc.c (ptw32_new): Change "new" variable to "t" to avoid - confusion with the C++ keyword of the same name. - - * condvar.c (cond_wait_cleanup): Initialise lastWaiter variable. - (cond_timedwait): Remove unused local variables. to avoid - compiler warnings. - - * dll.c (dllMain): Remove 2000-07-21 change - problem - appears to be in pthread_create(). - -2000-07-22 Ross Johnson - - * tsd.c (pthread_key_create): If a destructor was given - and the pthread_mutex_init failed, then would try to - reference a NULL pointer (*key); eliminate this section of - code by using a dynamically initialised mutex - (PTHREAD_MUTEX_INITIALIZER). - - * tsd.c (pthread_setspecific): Return an error if - unable to set the value; simplify cryptic conditional. - - * tsd.c (pthread_key_delete): Locking threadsLock relied - on mutex_lock returning an error if the key has no destructor. - ThreadsLock is only initialised if the key has a destructor. - Making this mutex a static could reduce the number of mutexes - used by an application since it is actually created only at - first use and it's often destroyed soon after. - -2000-07-22 Ross Johnson - - * FAQ: Added Q5 and Q6. - -2000-07-21 David Baggett - - * dll.c: Include resource leakage work-around. This is a - partial FIXME which doesn't stop all leakage. The real - problem needs to be found and fixed. - -2000-07-21 Ross Johnson - - * create.c (pthread_create): Set threadH to 0 (zero) - everywhere. Some assignments were using NULL. Maybe - it should be NULL everywhere - need to check. (I know - they are nearly always the same thing - but not by - definition.) - - * misc.c (pthread_self): Try to catch NULL thread handles - at the point where they might be generated, even though - they should always be valid at this point. - - * tsd.c (pthread_setspecific): return an error value if - pthread_self() returns NULL. - - * sync.c (pthread_join): return an error value if - pthread_self() returns NULL. - - * signal.c (pthread_sigmask): return an error value if - pthread_self() returns NULL. - -2000-03-02 Ross Johnson - - * attr.c (pthread_attr_init): Set default stacksize to zero (0) - rather than PTHREAD_STACK_MIN even though these are now the same. - - * pthread.h (PTHREAD_STACK_MIN): Lowered to 0. - -2000-01-28 Ross Johnson - - * mutex.c (pthread_mutex_init): Free mutex if it has been alloced; - if critical sections can be used instead of Win32 mutexes, test - that the critical section works and return an error if not. - -2000-01-07 Ross Johnson - - * cleanup.c (pthread_pop_cleanup): Include SEH code only if MSC is not - compiling as C++. - (pthread_push_cleanup): Include SEH code only if MSC is not - compiling as C++. - - * pthread.h: Include SEH code only if MSC is not - compiling as C++. - - * implement.h: Include SEH code only if MSC is not - compiling as C++. - - * cancel.c (ptw32_cancel_thread): Add _M_IX86 check. - (pthread_testcancel): Include SEH code only if MSC is not - compiling as C++. - (ptw32_cancel_self): Include SEH code only if MSC is not - compiling as C++. - -2000-01-06 Erik Hensema - - * Makefile: Remove inconsistencies in 'cl' args - -2000-01-04 Ross Johnson - - * private.c (ptw32_get_exception_services_code): New; returns - value of EXCEPTION_PTW32_SERVICES. - (ptw32_processInitialize): Remove initialisation of - ptw32_exception_services which is no longer needed. - - * pthread.h (ptw32_exception_services): Remove extern. - (ptw32_get_exception_services_code): Add function prototype; - use this to return EXCEPTION_PTW32_SERVICES value instead of - using the ptw32_exception_services variable which I had - trouble exporting through pthread.def. - - * global.c (ptw32_exception_services): Remove declaration. - -1999-11-22 Ross Johnson - - * implement.h: Forward declare ptw32_new(); - - * misc.c (ptw32_new): New; alloc and initialise a new pthread_t. - (pthread_self): New thread struct is generated by new routine - ptw32_new(). - - * create.c (pthread_create): New thread struct is generated - by new routine ptw32_new(). - -1999-11-21 Ross Johnson - - * global.c (ptw32_exception_services): Declare new variable. - - * private.c (ptw32_threadStart): Destroy thread's - cancelLock mutex; make 'catch' and '__except' usageimmune to - redfinitions in pthread.h. - (ptw32_processInitialize): Init new constant ptw32_exception_services. - - * create.c (pthread_create): Initialise thread's cancelLock - mutex. - - * cleanup.c (pthread_pop_cleanup): Make 'catch' and '__except' - usage immune to redfinition s in pthread.h. - - * private.c: Ditto. - - * pthread.h (catch): Redefine 'catch' so that C++ applications - won't catch our internal exceptions. - (__except): ditto for __except. - - * implement.h (ptw32_catch): Define internal version - of 'catch' because 'catch' is redefined by pthread.h. - (__except): ditto for __except. - (struct pthread_t_): Add cancelLock mutex for async cancel - safety. - -1999-11-21 Jason Nye , Erik Hensema - - * cancel.c (ptw32_cancel_self): New; part of the async - cancellation implementation. - (ptw32_cancel_thread): Ditto; this function is X86 - processor specific. - (pthread_setcancelstate): Add check for pending async - cancel request and cancel the calling thread if - required; add async-cancel safety lock. - (pthread_setcanceltype): Ditto. - -1999-11-13 Erik Hensema - - * configure.in (AC_OUTPUT): Put generated output into GNUmakefile - rather than Makefile. Makefile will become the MSC nmake compatible - version - -1999-11-13 John Bossom (John.Bossom@cognos.com> - - * misc.c (pthread_self): Add a note about GetCurrentThread - returning a pseudo-handle - -1999-11-10 Todd Owen - - * dll.c (dllMain): Free kernel32 ASAP. - If TryEnterCriticalSection is not being used, then free - the kernel32.dll handle now, rather than leaving it until - DLL_PROCESS_DETACH. - - Note: this is not a pedantic exercise in freeing unused - resources! It is a work-around for a bug in Windows 95 - (see microsoft knowledge base article, Q187684) which - does Bad Things when FreeLibrary is called within - the DLL_PROCESS_DETACH code, in certain situations. - Since w95 just happens to be a platform which does not - provide TryEnterCriticalSection, the bug will be - effortlessly avoided. - -1999-11-10 Ross Johnson - - * sync.c (pthread_join): Make it a deferred cancelation point. - - * misc.c (pthread_self): Explicitly initialise implicitly - created thread state to default values. - -1999-11-05 Tristan Savatier - - * pthread.h (winsock.h): Include unconditionally. - (ETIMEDOUT): Change fallback value to that defined by winsock.h. - - * general: Patched for portability to WinCE. The details are - described in the file WinCE-PORT. Follow the instructions - in README.WinCE to make the appropriate changes in config.h. - -1999-10-30 Erik Hensema - - * create.c (pthread_create): Explicitly initialise thread state to - default values. - - * cancel.c (pthread_setcancelstate): Check for NULL 'oldstate' - for compatibility with Solaris pthreads; - (pthread_setcanceltype): ditto: - -1999-10-23 Erik Hensema - - * pthread.h (ctime_r): Fix incorrect argument "_tm" - -1999-10-21 Aurelio Medina - - * pthread.h (_POSIX_THREADS): Only define it if it isn't - already defined. Projects may need to define this on - the CC command line under Win32 as it doesn't have unistd.h - -1999-10-17 Ross Johnson - - * rwlock.c (pthread_rwlock_destroy): Add cast to remove compile - warning. - - * condvar.c (pthread_cond_broadcast): Only release semaphores - if there are waiting threads. - -1999-10-15 Lorin Hochstein , Peter Slacik - - * condvar.c (cond_wait_cleanup): New static cleanup handler for - cond_timedwait; - (cond_timedwait): pthread_cleanup_push args changed; - canceling a thread while it's in pthread_cond_wait - will now decrement the waiters count and cleanup if it's the - last waiter. - -1999-10-15 Graham Dumpleton - - * condvar.c (cond_wait_cleanup): the last waiter will now reset the CV's - wasBroadcast flag - -Thu Sep 16 1999 Ross Johnson - - * rwlock.c (pthread_rwlock_destroy): Add serialisation. - (_rwlock_check_need_init): Check for detroyed rwlock. - * rwlock.c: Check return codes from _rwlock_check_need_init(); - modify comments; serialise access to rwlock objects during - operations; rename rw_mutex to rw_lock. - * implement.h: Rename rw_mutex to rw_lock. - * mutex.c (pthread_mutex_destroy): Add serialisation. - (_mutex_check_need_init): Check for detroyed mutex. - * condvar.c (pthread_cond_destroy): Add serialisation. - (_cond_check_need_init): Check for detroyed condvar. - * mutex.c: Modify comments. - * condvar.c: Modify comments. - -1999-08-10 Aurelio Medina - - * implement.h (pthread_rwlock_t_): Add. - * pthread.h (pthread_rwlock_t): Add. - (PTHREAD_RWLOCK_INITIALIZER): Add. - Add rwlock function prototypes. - * rwlock.c: New module. - * pthread.def: Add new rwlock functions. - * private.c (ptw32_processInitialize): initialise - ptw32_rwlock_test_init_lock critical section. - * global.c (ptw32_rwlock_test_init_lock): Add. - - * mutex.c (pthread_mutex_destroy): Don't free mutex memory - if mutex is PTHREAD_MUTEX_INITIALIZER and has not been - initialised yet. - -1999-08-08 Milan Gardian - - * mutex.c (pthread_mutex_destroy): Free mutex memory. - -1999-08-22 Ross Johnson - - * exit.c (pthread_exit): Fix reference to potentially - uninitialised pointer. - -1999-08-21 Ross Johnson - - * private.c (ptw32_threadStart): Apply fix of 1999-08-19 - this time to C++ and non-trapped C versions. Ommitted to - do this the first time through. - -1999-08-19 Ross Johnson - - * private.c (ptw32_threadStart): Return exit status from - the application thread startup routine. - - Milan Gardian - -1999-08-18 John Bossom - - * exit.c (pthread_exit): Put status into pthread_t->exitStatus - * private.c (ptw32_threadStart): Set pthread->exitStatus - on exit of try{} block. - * sync.c (pthread_join): use pthread_exitStatus value if the - thread exit doesn't return a value (for Mingw32 CRTDLL - which uses endthread instead of _endthreadex). - -Tue Aug 17 20:17:58 CDT 1999 Mumit Khan - - * create.c (pthread_create): Add CRTDLL suppport. - * exit.c (pthread_exit): Likewise. - * private.c (ptw32_threadStart): Likewise. - (ptw32_threadDestroy): Likewise. - * sync.c (pthread_join): Likewise. - * tests/join1.c (main): Warn about partial support for CRTDLL. - -Tue Aug 17 20:00:08 1999 Mumit Khan - - * Makefile.in (LD): Delete entry point. - * acconfig.h (STDCALL): Delete unused macro. - * configure.in: Remove test for STDCALL. - * config.h.in: Regenerate. - * errno.c (_errno): Fix self type. - * pthread.h (PT_STDCALL): Move from here to - * implement.h (PT_STDCALL): here. - (ptw32_threadStart): Fix prototype. - * private.c (ptw32_threadStart): Likewise. - -1999-08-14 Ross Johnson - - * exit.c (pthread_exit): Don't call pthread_self() but - get thread handle directly from TSD for efficiency. - -1999-08-12 Ross Johnson - - * private.c (ptw32_threadStart): ei[] only declared if _MSC_VER. - - * exit.c (pthread_exit): Check for implicitly created threads - to avoid raising an unhandled exception. - -1999-07-12 Peter Slacik - - * condvar.c (pthread_cond_destroy): Add critical section. - (cond_timedwait): Add critical section; check for timeout - waiting on semaphore. - (pthread_cond_broadcast): Add critical section. - -1999-07-09 Lorin Hochstein , John Bossom - - The problem was that cleanup handlers were not executed when - pthread_exit() was called. - - * implement.h (pthread_t_): Add exceptionInformation element for - C++ per-thread exception information. - (general): Define and rename exceptions. - -1999-07-09 Ross Johnson - - * misc.c (CancelableWait): PTW32_EPS_CANCEL (SEH) and - ptw32_exception_cancel (C++) used to identify the exception. - - * cancel.c (pthread_testcancel): PTW32_EPS_CANCEL (SEH) and - ptw32_exception_cancel (C++) used to identify the exception. - - * exit.c (pthread_exit): throw/raise an exception to return to - ptw32_threadStart() to exit the thread. PTW32_EPS_EXIT (SEH) - and ptw32_exception_exit (C++) used to identify the exception. - - * private.c (ptw32_threadStart): Add pthread_exit exception trap; - clean up and exit the thread directly rather than via pthread_exit(). - -Sun May 30 00:25:02 1999 Ross Johnson - - * semaphore.h (mode_t): Conditionally typedef it. - -Fri May 28 13:33:05 1999 Mark E. Armstrong - - * condvar.c (pthread_cond_broadcast): Fix possible memory fault - -Thu May 27 13:08:46 1999 Peter Slacik - - * condvar.c (pthread_cond_broadcast): Fix logic bug - -Thu May 27 13:08:46 1999 Bossom, John - - * condvar.c (pthread_cond_broadcast): optimise sem_post loop - -Fri May 14 12:13:18 1999 Mike Russo - - * attr.c (pthread_attr_setdetachstate): Fix logic bug - -Sat May 8 09:42:30 1999 Ross Johnson - - * pthread.def (sem_open): Add. - (sem_close): Add. - (sem_unlink): Add. - (sem_getvalue): Add. - - * FAQ (Question 3): Add. - -Thu Apr 8 01:16:23 1999 Ross Johnson - - * semaphore.c (sem_open): New function; returns an error (ENOSYS). - (sem_close): ditto. - (sem_unlink): ditto. - (sem_getvalue): ditto. - - * semaphore.h (_POSIX_SEMAPHORES): define. - -Wed Apr 7 14:09:52 1999 Ross Johnson - - * errno.c (_REENTRANT || _MT): Invert condition. - - * pthread.h (_errno): Conditionally include prototype. - -Wed Apr 7 09:37:00 1999 Ross Johnson - - * *.c (comments): Remove individual attributions - these are - documented sufficiently elsewhere. - - * implement.h (pthread.h): Remove extraneous include. - -Sun Apr 4 11:05:57 1999 Ross Johnson - - * sched.c (sched.h): Include. - - * sched.h: New file for POSIX 1b scheduling. - - * pthread.h: Move opaque structures to implement.h; move sched_* - prototypes out and into sched.h. - - * implement.h: Add opaque structures from pthread.h. - - * sched.c (sched_yield): New function. - - * condvar.c (ptw32_sem_*): Rename to sem_*; except for - ptw32_sem_timedwait which is an private function. - -Sat Apr 3 23:28:00 1999 Ross Johnson - - * Makefile.in (OBJS): Add errno.o. - -Fri Apr 2 11:08:50 1999 Ross Johnson - - * implement.h (ptw32_sem_*): Remove prototypes now defined in - semaphore.h. - - * pthread.h (sempahore.h): Include. - - * semaphore.h: New file for POSIX 1b semaphores. - - * semaphore.c (ptw32_sem_timedwait): Moved to private.c. - - * pthread.h (ptw32_sem_t): Change to sem_t. - - * private.c (ptw32_sem_timedwait): Moved from semaphore.c; - set errno on error. - - * pthread.h (pthread_t_): Add per-thread errno element. - -Fri Apr 2 11:08:50 1999 John Bossom - - * semaphore.c (ptw32_sem_*): Change to sem_*; these functions - will be exported from the library; set errno on error. - - * errno.c (_errno): New file. New function. - -Fri Mar 26 14:11:45 1999 Tor Lillqvist - - * semaphore.c (ptw32_sem_timedwait): Check for negative - milliseconds. - -Wed Mar 24 11:32:07 1999 John Bossom - - * misc.c (CancelableWait): Initialise exceptionInformation[2]. - (pthread_self): Get a real Win32 thread handle for implicit threads. - - * cancel.c (pthread_testcancel): Initialise exceptionInformation[2]. - - * implement.h (SE_INFORMATION): Fix values. - - * private.c (ptw32_threadDestroy): Close the thread handle. - -Fri Mar 19 12:57:27 1999 Ross Johnson - - * cancel.c (comments): Update and cleanup. - -Fri Mar 19 09:12:59 1999 Ross Johnson - - * private.c (ptw32_threadStart): status returns PTHREAD_CANCELED. - - * pthread.h (PTHREAD_CANCELED): defined. - -Tue Mar 16 1999 Ross Johnson - - * all: Add GNU LGPL and Copyright and Warranty. - -Mon Mar 15 00:20:13 1999 Ross Johnson - - * condvar.c (pthread_cond_init): fix possible uninitialised use - of cv. - -Sun Mar 14 21:01:59 1999 Ross Johnson - - * condvar.c (pthread_cond_destroy): don't do full cleanup if - static initialised cv has never been used. - (cond_timedwait): check result of auto-initialisation. - -Thu Mar 11 09:01:48 1999 Ross Johnson - - * pthread.h (pthread_mutex_t): revert to (pthread_mutex_t *); - define a value to serve as PTHREAD_MUTEX_INITIALIZER. - (pthread_mutex_t_): remove staticinit and valid elements. - (pthread_cond_t): revert to (pthread_cond_t_ *); - define a value to serve as PTHREAD_COND_INITIALIZER. - (pthread_cond_t_): remove staticinit and valid elements. - - * mutex.c (pthread_mutex_t args): adjust indirection of references. - (all functions): check for PTHREAD_MUTEX_INITIALIZER value; - check for NULL (invalid). - - * condvar.c (pthread_cond_t args): adjust indirection of references. - (all functions): check for PTHREAD_COND_INITIALIZER value; - check for NULL (invalid). - -Wed Mar 10 17:18:12 1999 Ross Johnson - - * misc.c (CancelableWait): Undo changes from Mar 8 and 7. - -Mon Mar 8 11:18:59 1999 Ross Johnson - - * misc.c (CancelableWait): Ensure cancelEvent handle is the lowest - indexed element in the handles array. Enhance test for abandoned - objects. - - * pthread.h (PTHREAD_MUTEX_INITIALIZER): Trailing elements not - initialised are set to zero by the compiler. This avoids the - problem of initialising the opaque critical section element in it. - (PTHREAD_COND_INITIALIZER): Ditto. - - * semaphore.c (ptw32_sem_timedwait): Check sem == NULL earlier. - -Sun Mar 7 12:31:14 1999 Ross Johnson - - * condvar.c (pthread_cond_init): set semaphore initial value - to 0, not 1. cond_timedwait was returning signaled immediately. - - * misc.c (CancelableWait): Place the cancel event handle first - in the handle table for WaitForMultipleObjects. This ensures that - the cancel event is recognised and acted apon if both objects - happen to be signaled together. - - * private.c (ptw32_cond_test_init_lock): Initialise and destroy. - - * implement.h (ptw32_cond_test_init_lock): Add extern. - - * global.c (ptw32_cond_test_init_lock): Add declaration. - - * condvar.c (pthread_cond_destroy): check for valid initialised CV; - flag destroyed CVs as invalid. - (pthread_cond_init): pthread_cond_t is no longer just a pointer. - This is because PTHREAD_COND_INITIALIZER needs state info to reside - in pthread_cond_t so that it can initialise on first use. Will work on - making pthread_cond_t (and other objects like it) opaque again, if - possible, later. - (cond_timedwait): add check for statically initialisation of - CV; initialise on first use. - (pthread_cond_signal): check for valid CV. - (pthread_cond_broadcast): check for valid CV. - (_cond_check_need_init): Add. - - * pthread.h (PTHREAD_COND_INITIALIZER): Fix. - (pthread_cond_t): no longer a pointer to pthread_cond_t_. - (pthread_cond_t_): add 'staticinit' and 'valid' elements. - -Sat Mar 6 1999 Ross Johnson - - * implement.h: Undate comments. - -Sun Feb 21 1999 Ross Johnson - - * pthread.h (PTHREAD_MUTEX_INITIALIZER): missing braces around - cs element initialiser. - -1999-02-21 Ben Elliston - - * pthread.h (pthread_exit): The return type of this function is - void, not int. - - * exit.c (pthread_exit): Do not return 0. - -Sat Feb 20 16:03:30 1999 Ross Johnson - - * dll.c (DLLMain): Expand TryEnterCriticalSection support test. - - * mutex.c (pthread_mutex_trylock): The check for - ptw32_try_enter_critical_section == NULL should have been - removed long ago. - -Fri Feb 19 16:03:30 1999 Ross Johnson - - * sync.c (pthread_join): Fix pthread_equal() test. - - * mutex.c (pthread_mutex_trylock): Check mutex != NULL before - using it. - -Thu Feb 18 16:17:30 1999 Ross Johnson - - * misc.c (pthread_equal): Fix inverted result. - - * Makefile.in: Use libpthread32.a as the name of the DLL export - library instead of pthread.lib. - - * condvar.c (pthread_cond_init): cv could have been used unitialised; - initialise. - - * create.c (pthread_create): parms could have been used unitialised; - initialise. - - * pthread.h (struct pthread_once_t_): Remove redefinition. - -Sat Feb 13 03:03:30 1999 Ross Johnson - - * pthread.h (struct pthread_once_t_): Replaced. - - * misc.c (pthread_once): Replace with John Bossom's version; - has lighter weight serialisation; fixes problem of not holding - competing threads until after the init_routine completes. - -Thu Feb 11 13:34:14 1999 Ross Johnson - - * misc.c (CancelableWait): Change C++ exception throw. - - * sync.c (pthread_join): Change FIXME comment - issue resolved. - -Wed Feb 10 12:49:11 1999 Ross Johnson - - * configure: Various temporary changes. - - Kevin Ruland - - * README: Update. - - * pthread.def (pthread_attr_getstackaddr): uncomment - (pthread_attr_setstackaddr): uncomment - -Fri Feb 5 13:42:30 1999 Ross Johnson - - * semaphore.c: Comment format changes. - -Thu Feb 4 10:07:28 1999 Ross Johnson - - * global.c: Remove ptw32_exception instantiation. - - * cancel.c (pthread_testcancel): Change C++ exception throw. - - * implement.h: Remove extern declaration. - -Wed Feb 3 13:04:44 1999 Ross Johnson - - * cleanup.c: Rename ptw32_*_cleanup() to pthread_*_cleanup(). - - * pthread.def: Ditto. - - * pthread.h: Ditto. - - * pthread.def (pthread_cleanup_push): Remove from export list; - the function is defined as a macro under all compilers. - (pthread_cleanup_pop): Ditto. - - * pthread.h: Remove #if defined(). - -Wed Feb 3 10:13:48 1999 Ross Johnson - - * sync.c (pthread_join): Check for NULL value_ptr arg; - check for detached threads. - -Tue Feb 2 18:07:43 1999 Ross Johnson - - * implement.h: Add #include . - Change sem_t to ptw32_sem_t. - -Tue Feb 2 18:07:43 1999 Kevin Ruland - - * signal.c (pthread_sigmask): Add and modify casts. - Reverse LHS/RHS bitwise assignments. - - * pthread.h: Remove #include . - (PTW32_ATTR_VALID): Add cast. - (struct pthread_t_): Add sigmask element. - - * dll.c: Add "extern C" for DLLMain. - (DllMain): Add cast. - - * create.c (pthread_create): Set sigmask in thread. - - * condvar.c: Remove #include. Change sem_* to ptw32_sem_*. - - * attr.c: Changed #include. - - * Makefile.in: Additional targets and changes to build the library - as a DLL. - -Fri Jan 29 11:56:28 1999 Ross Johnson - - * Makefile.in (OBJS): Add semaphore.o to list. - - * semaphore.c (ptw32_sem_timedwait): Move from private.c. - Rename sem_* to ptw32_sem_*. - - * pthread.h (pthread_cond_t): Change type of sem_t. - _POSIX_SEMAPHORES no longer defined. - - * semaphore.h: Contents moved to implement.h. - Removed from source tree. - - * implement.h: Add semaphore function prototypes and rename all - functions to prepend 'ptw32_'. They are - now private to the pthreads-win32 implementation. - - * private.c: Change #warning. - Move ptw32_sem_timedwait() to semaphore.c. - - * cleanup.c: Change #warning. - - * misc.c: Remove #include - - * pthread.def: Cleanup CVS merge conflicts. - - * global.c: Ditto. - - * ChangeLog: Ditto. - - * cleanup.c: Ditto. - -Sun Jan 24 01:34:52 1999 Ross Johnson - - * semaphore.c (sem_wait): Remove second arg to - pthreadCancelableWait() call. - -Sat Jan 23 17:36:40 1999 Ross Johnson - - * pthread.def: Add new functions to export list. - - * pthread.h (PTHREAD_MUTEX_AUTO_CS_NP): New. - (PTHREAD_MUTEX_FORCE_CS_NP): New. - - * README: Updated. - -Fri Jan 22 14:31:59 1999 Ross Johnson - - * Makefile.in (CFLAGS): Remove -fhandle-exceptions. Not needed - with egcs. Add -g for debugging. - - * create.c (pthread_create): Replace __stdcall with PT_STDCALL - macro. This is a hack and must be fixed. - - * misc.c (CancelableWait): Remove redundant statement. - - * mutex.c (pthread_mutexattr_init): Cast calloc return value. - - * misc.c (CancelableWait): Add cast. - (pthread_self): Add cast. - - * exit.c (pthread_exit): Add cast. - - * condvar.c (pthread_condattr_init): Cast calloc return value. - - * cleanup.c: Reorganise conditional compilation. - - * attr.c (pthread_attr_init): Remove unused 'result'. - Cast malloc return value. - - * private.c (ptw32_callUserDestroyRoutines): Redo conditional - compilation. - - * misc.c (CancelableWait): C++ version uses 'throw'. - - * cancel.c (pthread_testcancel): Ditto. - - * implement.h (class ptw32_exception): Define for C++. - - * pthread.h: Fix C, C++, and Win32 SEH condition compilation - mayhem around pthread_cleanup_* defines. C++ version now uses John - Bossom's cleanup handlers. - (pthread_attr_t): Make 'valid' unsigned. - Define '_timeb' as 'timeb' for Ming32. - Define PT_STDCALL as nothing for Mingw32. May be temporary. - - * cancel.c (pthread_testcancel): Cast return value. - -Wed Jan 20 09:31:28 1999 Ross Johnson - - * pthread.h (pthread_mutexattr_t): Changed to a pointer. - - * mutex.c (pthread_mutex_init): Conditionally create Win32 mutex - - from John Bossom's implementation. - (pthread_mutex_destroy): Conditionally close Win32 mutex - - from John Bossom's implementation. - (pthread_mutexattr_init): Replaced by John Bossom's version. - (pthread_mutexattr_destroy): Ditto. - (pthread_mutexattr_getpshared): New function from John Bossom's - implementation. - (pthread_mutexattr_setpshared): New function from John Bossom's - implementation. - -Tue Jan 19 18:27:42 1999 Ross Johnson - - * pthread.h (pthreadCancelableTimedWait): New prototype. - (pthreadCancelableWait): Remove second argument. - - * misc.c (CancelableWait): New static function is - pthreadCancelableWait() renamed. - (pthreadCancelableWait): Now just calls CancelableWait() with - INFINITE timeout. - (pthreadCancelableTimedWait): Just calls CancelableWait() - with passed in timeout. - -Tue Jan 19 18:27:42 1999 Scott Lightner - - * private.c (ptw32_sem_timedwait): 'abstime' arg really is - absolute time. Calculate relative time to wait from current - time before passing timeout to new routine - pthreadCancelableTimedWait(). - -Tue Jan 19 10:27:39 1999 Ross Johnson - - * pthread.h (pthread_mutexattr_setforcecs_np): New prototype. - - * mutex.c (pthread_mutexattr_init): Init 'pshared' and 'forcecs' - attributes to 0. - (pthread_mutexattr_setforcecs_np): New function (not portable). - - * pthread.h (pthread_mutex_t): - Add 'mutex' element. Set to NULL in PTHREAD_MUTEX_INITIALIZER. - The pthread_mutex_*() routines will try to optimise performance - by choosing either mutexes or critical sections as the basis - for pthread mutexes for each indevidual mutex. - (pthread_mutexattr_t_): Add 'forcecs' element. - Some applications may choose to force use of critical sections - if they know that:- - the mutex is PROCESS_PRIVATE and, - either the OS supports TryEnterCriticalSection() or - pthread_mutex_trylock() will never be called on the mutex. - This attribute will be setable via a non-portable routine. - - Note: We don't yet support PROCESS_SHARED mutexes, so the - implementation as it stands will default to Win32 mutexes only if - the OS doesn't support TryEnterCriticalSection. On Win9x, and early - versions of NT 'forcecs' will need to be set in order to get - critical section based mutexes. - -Sun Jan 17 12:01:26 1999 Ross Johnson - - * pthread.h (PTHREAD_MUTEX_INITIALIZER): Init new 'staticinit' - value to '1' and existing 'valid' value to '1'. - - * global.c (ptw32_mutex_test_init_lock): Add. - - * implement.h (ptw32_mutex_test_init_lock.): Add extern. - - * private.c (ptw32_processInitialize): Init critical section for - global lock used by _mutex_check_need_init(). - (ptw32_processTerminate): Ditto (:s/Init/Destroy/). - - * dll.c (dllMain): Move call to FreeLibrary() so that it is only - called once when the process detaches. - - * mutex.c (_mutex_check_need_init): New static function to test - and init PTHREAD_MUTEX_INITIALIZER mutexes. Provides serialised - access to the internal state of the uninitialised static mutex. - Called from pthread_mutex_trylock() and pthread_mutex_lock() which - do a quick unguarded test to check if _mutex_check_need_init() - needs to be called. This is safe as the test is conservative - and is repeated inside the guarded section of - _mutex_check_need_init(). Thus in all calls except the first - calls to lock static mutexes, the additional overhead to lock any - mutex is a single memory fetch and test for zero. - - * pthread.h (pthread_mutex_t_): Add 'staticinit' member. Mutexes - initialised by PTHREAD_MUTEX_INITIALIZER aren't really initialised - until the first attempt to lock it. Using the 'valid' - flag (which flags the mutex as destroyed or not) to record this - information would be messy. It is possible for a statically - initialised mutex such as this to be destroyed before ever being - used. - - * mutex.c (pthread_mutex_trylock): Call _mutex_check_need_init() - to test/init PTHREAD_MUTEX_INITIALIZER mutexes. - (pthread_mutex_lock): Ditto. - (pthread_mutex_unlock): Add check to ensure we don't try to unlock - an unitialised static mutex. - (pthread_mutex_destroy): Add check to ensure we don't try to delete - a critical section that we never created. Allows us to destroy - a static mutex that has never been locked (and hence initialised). - (pthread_mutex_init): Set 'staticinit' flag to 0 for the new mutex. - -Sun Jan 17 12:01:26 1999 Ross Johnson - - * private.c (ptw32_sem_timedwait): Move from semaphore.c. - - * semaphore.c : Remove redundant #includes. - (ptw32_sem_timedwait): Move to private.c. - (sem_wait): Add missing abstime arg to pthreadCancelableWait() call. - -Fri Jan 15 23:38:05 1999 Ross Johnson - - * condvar.c (cond_timedwait): Remove comment. - -Fri Jan 15 15:41:28 1999 Ross Johnson - - * pthread.h: Add new 'abstime' arg to pthreadCancelableWait() - prototype. - - * condvar.c (cond_timedwait): New generalised function called by - both pthread_cond_wait() and pthread_cond_timedwait(). This is - essentially pthread_cond_wait() renamed and modified to add the - 'abstime' arg and call the new ptw32_sem_timedwait() instead of - sem_wait(). - (pthread_cond_wait): Now just calls the internal static - function cond_timedwait() with an INFINITE wait. - (pthread_cond_timedwait): Now implemented. Calls the internal - static function cond_timedwait(). - - * implement.h (ptw32_sem_timedwait): New internal function - prototype. - - * misc.c (pthreadCancelableWait): Added new 'abstime' argument - to allow shorter than INFINITE wait. - - * semaphore.c (ptw32_sem_timedwait): New function for internal - use. This is essentially sem_wait() modified to add the - 'abstime' arg and call the modified (see above) - pthreadCancelableWait(). - -Thu Jan 14 14:27:13 1999 Ross Johnson - - * cleanup.c: Correct _cplusplus to __cplusplus wherever used. - - * Makefile.in: Add CC=g++ and add -fhandle-exceptions to CFLAGS. - The derived Makefile will compile all units of the package as C++ - so that those which include try/catch exception handling should work - properly. The package should compile ok if CC=gcc, however, exception - handling will not be included and thus thread cancellation, for - example, will not work. - - * cleanup.c (ptw32_pop_cleanup): Add #warning to compile this - file as C++ if using a cygwin32 environment. Perhaps the whole package - should be compiled using g++ under cygwin. - - * private.c (ptw32_threadStart): Change #error directive - into #warning and bracket for __CYGWIN__ and derivative compilers. - -Wed Jan 13 09:34:52 1999 Ross Johnson - - * build.bat: Delete old binaries before compiling/linking. - -Tue Jan 12 09:58:38 1999 Tor Lillqvist - - * dll.c: The Microsoft compiler pragmas probably are more - appropriately protected by _MSC_VER than by _WIN32. - - * pthread.h: Define ETIMEDOUT. This should be returned by - pthread_cond_timedwait which is not implemented yet as of - snapshot-1999-01-04-1305. It was implemented in the older version. - The Microsoft compiler pragmas probably are more appropriately - protected by _MSC_VER than by _WIN32. - - * pthread.def: pthread_mutex_destroy was missing from the def file - - * condvar.c (pthread_cond_broadcast): Ensure we only wait on threads - if there were any waiting on the condition. - I think pthread_cond_broadcast should do the WaitForSingleObject - only if cv->waiters > 0? Otherwise it seems to hang, at least in the - testg thread program from glib. - -Tue Jan 12 09:58:38 1999 Ross Johnson - - * condvar.c (pthread_cond_timedwait): Fix function description - comments. - - * semaphore.c (sem_post): Correct typo in comment. - -Mon Jan 11 20:33:19 1999 Ross Johnson - - * pthread.h: Re-arrange conditional compile of pthread_cleanup-* - macros. - - * cleanup.c (ptw32_push_cleanup): Provide conditional - compile of cleanup->prev. - -1999-01-11 Tor Lillqvist - - * condvar.c (pthread_cond_init): Invert logic when testing the - return value from calloc(). - -Sat Jan 9 14:32:08 1999 Ross Johnson - - * implement.h: Compile-time switch for CYGWIN derived environments - to use CreateThread instead of _beginthreadex. Ditto for ExitThread. - Patch provided by Anders Norlander . - -Tue Jan 5 16:33:04 1999 Ross Johnson - - * cleanup.c (ptw32_pop_cleanup): Add C++ version of __try/__except - block. Move trailing "}" out of #ifdef _WIN32 block left there by - (rpj's) mistake. - - * private.c: Remove #include which is included by pthread.h. - -1998-12-11 Ben Elliston - - * README: Update info about subscribing to the mailing list. - -Mon Jan 4 11:23:40 1999 Ross Johnson - - * all: No code changes, just cleanup. - - remove #if 0 /* Pre Bossom */ enclosed code. - - Remove some redundant #includes. - * pthread.h: Update implemented/unimplemented routines list. - * Tag the bossom merge branch getting ready to merge back to main - trunk. - -Tue Dec 29 13:11:16 1998 Ross Johnson - - * implement.h: Move the following struct definitions to pthread.h: - pthread_t_, pthread_attr_t_, pthread_mutex_t_, pthread_mutex_t_, - pthread_mutexattr_t_, pthread_key_t_, pthread_cond_t_, - pthread_condattr_t_, pthread_once_t_. - - * pthread.h: Add "_" prefix to pthread_push_cleanup and - pthread_pop_cleanup internal routines, and associated struct and - typedefs. - - * buildlib.bat: Add compile command for semaphore.c - - * pthread.def: Comment out pthread_atfork routine name. - Now unimplemented. - - * tsd.c (pthread_setspecific): Rename tkAssocCreate to - ptw32_tkAssocCreate. - (pthread_key_delete): Rename tkAssocDestroy to - ptw32_tkAssocDestroy. - - * sync.c (pthread_join): Rename threadDestroy to ptw32_threadDestroy - - * sched.c (is_attr): attr is now **attr (was *attr), so add extra - NULL pointer test. - (pthread_attr_setschedparam): Increase redirection for attr which is - now a **. - (pthread_attr_getschedparam): Ditto. - (pthread_setschedparam): Change thread validation and rename "thread" - Win32 thread Handle element name to match John Bossom's version. - (pthread_getschedparam): Ditto. - - * private.c (ptw32_threadDestroy): Rename call to - callUserDestroyRoutines() as ptw32_callUserDestroyRoutines() - - * misc.c: Add #include "implement.h". - - * dll.c: Remove defined(KLUDGE) wrapped code. - - * fork.c: Remove redefinition of ENOMEM. - Remove pthread_atfork() and fork() with #if 0/#endif. - - * create.c (pthread_create): Rename threadStart and threadDestroy calls - to ptw32_threadStart and ptw32_threadDestroy. - - * implement.h: Rename "detachedstate" to "detachstate". - - * attr.c: Rename "detachedstate" to "detachstate". - -Mon Dec 28 09:54:39 1998 John Bossom - - * semaphore.c: Initial version. - * semaphore.h: Initial version. - -Mon Dec 28 09:54:39 1998 Ross Johnson - - * pthread.h (pthread_attr_t_): Change to *pthread_attr_t. - -Mon Dec 28 09:54:39 1998 John Bossom, Ben Elliston - - * attr.c (pthread_attr_setstacksize): Merge with John's version. - (pthread_attr_getstacksize): Merge with John's version. - (pthread_attr_setstackaddr): Merge with John's version. - (pthread_attr_getstackaddr): Merge with John's version. - (pthread_attr_init): Merge with John's version. - (pthread_attr_destroy): Merge with John's version. - (pthread_attr_getdetachstate): Merge with John's version. - (pthread_attr_setdetachstate): Merge with John's version. - (is_attr): attr is now **attr (was *attr), so add extra NULL pointer - test. - -Mon Dec 28 09:54:39 1998 Ross Johnson - - * implement.h (pthread_attr_t_): Add and rename elements in JEB's - version to correspond to original, so that it can be used with - original attr routines. - - * pthread.h: Add #endif at end which was truncated in merging. - -Sun Dec 20 14:51:58 1998 Ross Johnson - - * misc.c (pthreadCancelableWait): New function by John Bossom. Non-standard - but provides a hook that can be used to implement cancellation points in - applications that use this library. - - * pthread.h (pthread_cleanup_pop): C++ (non-WIN32) version uses - try/catch to emulate John Bossom's WIN32 __try/__finally behaviour. - In the WIN32 version __finally block, add a test for AbnormalTermination otherwise - cleanup is only run if the cleanup_pop execute arg is non-zero. Cancellation - should cause the cleanup to run irrespective of the execute arg. - - * condvar.c (pthread_condattr_init): Replaced by John Bossom's version. - (pthread_condattr_destroy): Replaced by John Bossom's version. - (pthread_condattr_getpshared): Replaced by John Bossom's version. - (pthread_condattr_setpshared): Replaced by John Bossom's version. - (pthread_cond_init): Replaced by John Bossom's version. - Fix comment (refered to mutex rather than condition variable). - (pthread_cond_destroy): Replaced by John Bossom's version. - (pthread_cond_wait): Replaced by John Bossom's version. - (pthread_cond_timedwait): Replaced by John Bossom's version. - (pthread_cond_signal): Replaced by John Bossom's version. - (pthread_cond_broadcast): Replaced by John Bossom's version. - -Thu Dec 17 19:10:46 1998 Ross Johnson - - * tsd.c (pthread_key_create): Replaced by John Bossom's version. - (pthread_key_delete): Replaced by John Bossom's version. - (pthread_setspecific): Replaced by John Bossom's version. - (pthread_getspecific): Replaced by John Bossom's version. - -Mon Dec 7 09:44:40 1998 John Bossom - - * cancel.c (pthread_setcancelstate): Replaced. - (pthread_setcanceltype): Replaced. - (pthread_testcancel): Replaced. - (pthread_cancel): Replaced. - - * exit.c (pthread_exit): Replaced. - - * misc.c (pthread_self): Replaced. - (pthread_equal): Replaced. - - * sync.c (pthread_detach): Replaced. - (pthread_join): Replaced. - - * create.c (pthread_create): Replaced. - - * private.c (ptw32_processInitialize): New. - (ptw32_processTerminate): New. - (ptw32_threadStart): New. - (ptw32_threadDestroy): New. - (ptw32_cleanupStack): New. - (ptw32_tkAssocCreate): New. - (ptw32_tkAssocDestroy): New. - (ptw32_callUserDestroyRoutines): New. - - * implement.h: Added non-API structures and declarations. - - * dll.c (PthreadsEntryPoint): Cast return value of GetProcAddress - to resolve compile warning from MSVC. - - * dll.c (DLLmain): Replaced. - * dll.c (PthreadsEntryPoint): - Re-applied Anders Norlander's patch:- - Initialize ptw32_try_enter_critical_section at startup - and release kernel32 handle when DLL is being unloaded. - -Sun Dec 6 21:54:35 1998 Ross Johnson - - * buildlib.bat: Fix args to CL when building the .DLL - - * cleanup.c (ptw32_destructor_run_all): Fix TSD key management. - This is a tidy-up before TSD and Thread management is completely - replaced by John Bossom's code. - - * tsd.c (pthread_key_create): Fix TSD key management. - - * global.c (ptw32_key_virgin_next): Initialise. - - * build.bat: New DOS script to compile and link a pthreads app - using Microsoft's CL compiler linker. - * buildlib.bat: New DOS script to compile all the object files - and create pthread.lib and pthread.dll using Microsoft's CL - compiler linker. - -1998-12-05 Anders Norlander - - * implement.h (ptw32_try_enter_critical_section): New extern - * dll.c (ptw32_try_enter_critical_section): New pointer to - TryEnterCriticalSection if it exists; otherwise NULL. - * dll.c (PthreadsEntryPoint): - Initialize ptw32_try_enter_critical_section at startup - and release kernel32 handle when DLL is being unloaded. - * mutex.c (pthread_mutex_trylock): Replaced check for NT with - a check if ptw32_try_enter_critical_section is valid - pointer to a function. Call ptw32_try_enter_critical_section - instead of TryEnterCriticalSection to avoid errors on Win95. - -Thu Dec 3 13:32:00 1998 Ross Johnson - - * README: Correct cygwin32 compatibility statement. - -Sun Nov 15 21:24:06 1998 Ross Johnson - - * cleanup.c (ptw32_destructor_run_all): Declare missing void * arg. - Fixup CVS merge conflicts. - -1998-10-30 Ben Elliston - - * condvar.c (cond_wait): Fix semantic error. Test for equality - instead of making an assignment. - -Fri Oct 30 15:15:50 1998 Ross Johnson - - * cleanup.c (ptw32_handler_push): Fixed bug appending new - handler to list reported by Peter Slacik - . - (new_thread): Rename poorly named local variable to - "new_handler". - -Sat Oct 24 18:34:59 1998 Ross Johnson - - * global.c: Add TSD key management array and index declarations. - - * implement.h: Ditto for externs. - -Fri Oct 23 00:08:09 1998 Ross Johnson - - * implement.h (PTW32_TSD_KEY_REUSE): Add enum. - - * private.c (ptw32_delete_thread): Add call to - ptw32_destructor_run_all() to clean up the threads keys. - - * cleanup.c (ptw32_destructor_run_all): Check for no more dirty - keys to run destructors on. Assume that the destructor call always - succeeds and set the key value to NULL. - -Thu Oct 22 21:44:44 1998 Ross Johnson - - * tsd.c (pthread_setspecific): Add key management code. - (pthread_key_create): Ditto. - (pthread_key_delete): Ditto. - - * implement.h (struct ptw32_tsd_key): Add status member. - - * tsd.c: Add description of pthread_key_delete() from the - standard as a comment. - -Fri Oct 16 17:38:47 1998 Ross Johnson - - * cleanup.c (ptw32_destructor_run_all): Fix and improve - stepping through the key table. - -Thu Oct 15 14:05:01 1998 Ross Johnson - - * private.c (ptw32_new_thread): Remove init of destructorstack. - No longer an element of pthread_t. - - * tsd.c (pthread_setspecific): Fix type declaration and cast. - (pthread_getspecific): Ditto. - (pthread_getspecific): Change error return value to NULL if key - is not in use. - -Thu Oct 15 11:53:21 1998 Ross Johnson - - * global.c (ptw32_tsd_key_table): Fix declaration. - - * implement.h(ptw32_TSD_keys_TlsIndex): Add missing extern. - (ptw32_tsd_mutex): Ditto. - - * create.c (ptw32_start_call): Fix "keys" array declaration. - Add comment. - - * tsd.c (pthread_setspecific): Fix type declaration and cast. - (pthread_getspecific): Ditto. - - * cleanup.c (ptw32_destructor_run_all): Declare missing loop - counter. - -Wed Oct 14 21:09:24 1998 Ross Johnson - - * private.c (ptw32_new_thread): Increment ptw32_threads_count. - (ptw32_delete_thread): Decrement ptw32_threads_count. - Remove some comments. - - * exit.c (ptw32_exit): : Fix two pthread_mutex_lock() calls that - should have been pthread_mutex_unlock() calls. - (ptw32_vacuum): Remove call to ptw32_destructor_pop_all(). - - * create.c (pthread_create): Fix two pthread_mutex_lock() calls that - should have been pthread_mutex_unlock() calls. - - * global.c (ptw32_tsd_mutex): Add mutex for TSD operations. - - * tsd.c (pthread_key_create): Add critical section. - (pthread_setspecific): Ditto. - (pthread_getspecific): Ditto. - (pthread_key_delete): Ditto. - - * sync.c (pthread_join): Fix two pthread_mutex_lock() calls that - should have been pthread_mutex_unlock() calls. - -Mon Oct 12 00:00:44 1998 Ross Johnson - - * implement.h (ptw32_tsd_key_table): New. - - * create.c (ptw32_start_call): Initialise per-thread TSD keys - to NULL. - - * misc.c (pthread_once): Correct typo in comment. - - * implement.h (ptw32_destructor_push): Remove. - (ptw32_destructor_pop): Remove. - (ptw32_destructor_run_all): Rename from ptw32_destructor_pop_all. - (PTW32_TSD_KEY_DELETED): Add enum. - (PTW32_TSD_KEY_INUSE): Add enum. - - * cleanup.c (ptw32_destructor_push): Remove. - (ptw32_destructor_pop): Remove. - (ptw32_destructor_run_all): Totally revamped TSD. - - * dll.c (ptw32_TSD_keys_TlsIndex): Initialise. - - * tsd.c (pthread_setspecific): Totally revamped TSD. - (pthread_getspecific): Ditto. - (pthread_create): Ditto. - (pthread_delete): Ditto. - -Sun Oct 11 22:44:55 1998 Ross Johnson - - * global.c (ptw32_tsd_key_table): Add new global. - - * implement.h (ptw32_tsd_key_t and struct ptw32_tsd_key): - Add. - (struct _pthread): Remove destructorstack. - - * cleanup.c (ptw32_destructor_run_all): Rename from - ptw32_destructor_pop_all. The key destructor stack was made - global rather than per-thread. No longer removes destructor nodes - from the stack. Comments updated. - -1998-10-06 Ben Elliston - - * condvar.c (cond_wait): Use POSIX, not Win32 mutex calls. - (pthread_cond_broadcast): Likewise. - (pthread_cond_signal): Likewise. - -1998-10-05 Ben Elliston - - * pthread.def: Update. Some functions aren't available yet, others - are macros in . - - * tests/join.c: Remove; useless. - -Mon Oct 5 14:25:08 1998 Ross Johnson - - * pthread.def: New file for building the DLL. - -1998-10-05 Ben Elliston - - * misc.c (pthread_equal): Correct inverted logic bug. - (pthread_once): Use the POSIX mutex primitives, not Win32. Remove - irrelevant FIXME comment. - - * global.c (PTHREAD_MUTEX_INITIALIZER): Move to pthread.h. - - * pthread.h (PTHREAD_MUTEX_INITIALIZER): Define. - (pthread_mutex_t): Reimplement as a struct containing a valid - flag. If the flag is ever down upon entry to a mutex operation, - we call pthread_mutex_create() to initialise the object. This - fixes the problem of how to handle statically initialised objects - that can't call InitializeCriticalSection() due to their context. - (PTHREAD_ONCE_INIT): Define. - - * mutex.c (pthread_mutex_init): Set valid flag. - (pthread_mutex_destroy): Clear valid flag. - (pthread_mutex_lock): Check and handle the valid flag. - (pthread_mutex_unlock): Likewise. - (pthread_mutex_trylock): Likewise. - - * tests/mutex3.c: New file; test for the static initialisation - macro. Passes. - - * tests/create1.c: New file; test pthread_create(). Passes. - - * tests/equal.c: Poor test; remove. - - * tests/equal1.c New file; test pthread_equal(). Passes. - - * tests/once1.c: New file; test for pthread_once(). Passes. - - * tests/self.c: Remove; rename to self1.c. - - * tests/self1.c: This is the old self.c. - - * tests/self2.c: New file. Test pthread_self() with a single - thread. Passes. - - * tests/self3.c: New file. Test pthread_self() with a couple of - threads to ensure their thread IDs differ. Passes. - -1998-10-04 Ben Elliston - - * tests/mutex2.c: Test pthread_mutex_trylock(). Passes. - - * tests/mutex1.c: New basic test for mutex functions (it passes). - (main): Eliminate warning. - - * configure.in: Test for __stdcall, not _stdcall. Typo. - - * configure: Regenerate. - - * attr.c (pthread_attr_setstackaddr): Remove FIXME comment. Win32 - does know about ENOSYS after all. - (pthread_attr_setstackaddr): Likewise. - -1998-10-03 Ben Elliston - - * configure.in: Test for the `_stdcall' keyword. Define `STDCALL' - to `_stdcall' if we have it, null otherwise. - - * configure: Regenerate. - - * acconfig.h (STDCALL): New define. - - * config.h.in: Regenerate. - - * create.c (ptw32_start_call): Add STDCALL prefix. - - * mutex.c (pthread_mutex_init): Correct function signature. - - * attr.c (pthread_attr_init): Only zero out the `sigmask' member - if we have the sigset_t type. - - * pthread.h: No need to include . It doesn't even exist - on Win32! Again, an artifact of cross-compilation. - (pthread_sigmask): Only provide if we have the sigset_t type. - - * process.h: Remove. This was a stand-in before we started doing - native compilation under Win32. - - * pthread.h (pthread_mutex_init): Make `attr' argument const. - -1998-10-02 Ben Elliston - - * COPYING: Remove. - - * COPYING.LIB: Add. This library is under the LGPL. - -1998-09-13 Ben Elliston - - * configure.in: Test for required system features. - - * configure: Generate. - - * acconfig.h: New file. - - * config.h.in: Generate. - - * Makefile.in: Renamed from Makefile. - - * COPYING: Import from a recent GNU package. - - * config.guess: Likewise. - - * config.sub: Likewise. - - * install-sh: Likewise. - - * config.h: Remove. - - * Makefile: Likewise. - -1998-09-12 Ben Elliston - - * windows.h: No longer needed; remove. - - * windows.c: Likewise. - -Sat Sep 12 20:09:24 1998 Ross Johnson - - * windows.h: Remove error number definitions. These are in - - * tsd.c: Add comment explaining rationale for not building - POSIX TSD on top of Win32 TLS. - -1998-09-12 Ben Elliston - - * {most}.c: Include to get POSIX error values. - - * signal.c (pthread_sigmask): Only provide if HAVE_SIGSET_T is - defined. - - * config.h: #undef features, don't #define them. This will be - generated by autoconf very soon. - -1998-08-11 Ben Elliston - - * Makefile (LIB): Define. - (clean): Define target. - (all): Build a library not just the object files. - - * pthread.h: Provide a definition for struct timespec if we don't - already have one. - - * windows.c (TlsGetValue): Bug fix. - -Thu Aug 6 15:19:22 1998 Ross Johnson - - * misc.c (pthread_once): Fix arg 1 of EnterCriticalSection() - and LeaveCriticalSection() calls to pass address-of lock. - - * fork.c (pthread_atfork): Typecast (void (*)(void *)) funcptr - in each ptw32_handler_push() call. - - * exit.c (ptw32_exit): Fix attr arg in - pthread_attr_getdetachstate() call. - - * private.c (ptw32_new_thread): Typecast (HANDLE) NULL. - (ptw32_delete_thread): Ditto. - - * implement.h: (PTW32_MAX_THREADS): Add define. This keeps - changing in an attempt to make thread administration data types - opaque and cleanup DLL startup. - - * dll.c (PthreadsEntryPoint): - (ptw32_virgins): Remove malloc() and free() calls. - (ptw32_reuse): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * global.c (_POSIX_THREAD_THREADS_MAX): Initialise with - PTW32_MAX_THREADS. - (ptw32_virgins): Ditto. - (ptw32_reuse): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * create.c (pthread_create): Typecast (HANDLE) NULL. - Typecast (unsigned (*)(void *)) start_routine. - - * condvar.c (pthread_cond_init): Add address-of operator & to - arg 1 of pthread_mutex_init() call. - (pthread_cond_destroy): Add address-of operator & to - arg 1 of pthread_mutex_destroy() call. - - * cleanup.c (ptw32_destructor_pop_all): Add (int) cast to - pthread_getspecific() arg. - (ptw32_destructor_pop): Add (void *) cast to "if" conditional. - (ptw32_destructor_push): Add (void *) cast to - ptw32_handler_push() "key" arg. - (malloc.h): Add include. - - * implement.h (ptw32_destructor_pop): Add prototype. - - * tsd.c (implement.h): Add include. - - * sync.c (pthread_join): Remove target_thread_mutex and it's - initialisation. Rename getdetachedstate to getdetachstate. - Remove unused variable "exitcode". - (pthread_detach): Remove target_thread_mutex and it's - initialisation. Rename getdetachedstate to getdetachstate. - Rename setdetachedstate to setdetachstate. - - * signal.c (pthread_sigmask): Rename SIG_SET to SIG_SETMASK. - Cast "set" to (long *) in assignment to passify compiler warning. - Add address-of operator & to thread->attr.sigmask in memcpy() call - and assignment. - (pthread_sigmask): Add address-of operator & to thread->attr.sigmask - in memcpy() call and assignment. - - * windows.h (THREAD_PRIORITY_ERROR_RETURN): Add. - (THREAD_PRIORITY_LOWEST): Add. - (THREAD_PRIORITY_HIGHEST): Add. - - * sched.c (is_attr): Add function. - (implement.h): Add include. - (pthread_setschedparam): Rename all instances of "sched_policy" - to "sched_priority". - (pthread_getschedparam): Ditto. - -Tue Aug 4 16:57:58 1998 Ross Johnson - - * private.c (ptw32_delete_thread): Fix typo. Add missing ';'. - - * global.c (ptw32_virgins): Change types from pointer to - array pointer. - (ptw32_reuse): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * implement.h(ptw32_virgins): Change types from pointer to - array pointer. - (ptw32_reuse): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * private.c (ptw32_delete_thread): Fix "entry" should be "thread". - - * misc.c (pthread_self): Add extern for ptw32_threadID_TlsIndex. - - * global.c: Add comment. - - * misc.c (pthread_once): Fix member -> dereferences. - Change ptw32_once_flag to once_control->flag in "if" test. - -Tue Aug 4 00:09:30 1998 Ross Johnson - - * implement.h(ptw32_virgins): Add extern. - (ptw32_virgin_next): Ditto. - (ptw32_reuse): Ditto. - (ptw32_reuse_top): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * global.c (ptw32_virgins): Changed from array to pointer. - Storage allocation for the array moved into dll.c. - (ptw32_reuse): Ditto. - (ptw32_win32handle_map): Ditto. - (ptw32_threads_mutex_table): Ditto. - - * dll.c (PthreadsEntryPoint): Set up thread admin storage when - DLL is loaded. - - * fork.c (pthread_atfork): Fix function pointer arg to all - ptw32_handler_push() calls. Change "arg" arg to NULL in child push. - - * exit.c: Add windows.h and process.h includes. - (ptw32_exit): Add local detachstate declaration. - (ptw32_exit): Fix incorrect name for pthread_attr_getdetachstate(). - - * pthread.h (_POSIX_THREAD_ATTR_STACKSIZE): Move from global.c - (_POSIX_THREAD_ATTR_STACKADDR): Ditto. - - * create.c (pthread_create): Fix #if should be #ifdef. - (ptw32_start_call): Remove usused variables. - - * process.h: Create. - - * windows.h: Move _beginthreadex and _endthreadex into - process.h - -Mon Aug 3 21:19:57 1998 Ross Johnson - - * condvar.c (pthread_cond_init): Add NULL attr to - pthread_mutex_init() call - default attributes will be used. - (cond_wait): Fix typo. - (cond_wait): Fix typo - cv was ev. - (pthread_cond_broadcast): Fix two identical typos. - - * cleanup.c (ptw32_destructor_pop_all): Remove _ prefix from - PTHREAD_DESTRUCTOR_ITERATIONS. - - * pthread.h: Move _POSIX_* values into posix.h - - * pthread.h: Fix typo in pthread_mutex_init() prototype. - - * attr.c (pthread_attr_init): Fix error in priority member init. - - * windows.h (THREAD_PRIORITY_NORMAL): Add. - - * pthread.h (sched_param): Add missing ';' to struct definition. - - * attr.c (pthread_attr_init): Remove obsolete pthread_attr_t - member initialisation - cancelstate, canceltype, cancel_pending. - (is_attr): Make arg "attr" a const. - - * implement.h (PTW32_HANDLER_POP_LIFO): Remove definition. - (PTW32_HANDLER_POP_FIFO): Ditto. - (PTW32_VALID): Add missing newline escape (\). - (ptw32_handler_node): Make element "next" a pointer. - -1998-08-02 Ben Elliston - - * windows.h: Remove duplicate TlsSetValue() prototype. Add - TlsGetValue() prototype. - (FALSE): Define. - (TRUE): Likewise. - Add forgotten errno values. Guard against multiple #includes. - - * windows.c: New file. Implement stubs for Win32 functions. - - * Makefile (SRCS): Remove. Not explicitly needed. - (CFLAGS): Add -Wall for all warnings with GCC. - -Sun Aug 2 19:03:42 1998 Ross Johnson - - * config.h: Create. This is a temporary stand-in for autoconf yet - to be done. - (HAVE_SIGNAL_H): Add. - - * pthread.h: Minor rearrangement for temporary config.h. - -Fri Jul 31 14:00:29 1998 Ross Johnson - - * cleanup.c (ptw32_destructor_pop): Implement. Removes - destructors associated with a key without executing them. - (ptw32_destructor_pop_all): Add FIXME comment. - - * tsd.c (pthread_key_delete): Add call to ptw32_destructor_pop(). - -Fri Jul 31 00:05:45 1998 Ross Johnson - - * tsd.c (pthread_key_create): Update to properly associate - the destructor routine with the key. - (pthread_key_delete): Add FIXME comment. - - * exit.c (ptw32_vacuum): Add call to - ptw32_destructor_pop_all(). - - * implement.h (ptw32_handler_pop_all): Add prototype. - (ptw32_destructor_pop_all): Ditto. - - * cleanup.c (ptw32_destructor_push): Implement. This is just a - call to ptw32_handler_push(). - (ptw32_destructor_pop_all): Implement. This is significantly - different to ptw32_handler_pop_all(). - - * Makefile (SRCS): Create. Preliminary. - - * windows.h: Create. Contains Win32 definitions for compile - testing. This is just a standin for the real one. - - * pthread.h (SIG_UNBLOCK): Fix typo. Was SIG_BLOCK. - (windows.h): Add include. Required for CRITICAL_SECTION. - (pthread_cond_t): Move enum declaration outside of struct - definition. - (unistd.h): Add include - may be temporary. - - * condvar.c (windows.h): Add include. - - * implement.h (PTW32_THIS): Remove - no longer required. - (PTW32_STACK): Use pthread_self() instead of PTW32_THIS. - -Thu Jul 30 23:12:45 1998 Ross Johnson - - * implement.h: Remove ptw32_find_entry() prototype. - - * private.c: Extend comments. - Remove ptw32_find_entry() - no longer needed. - - * create.c (ptw32_start_call): Add call to TlsSetValue() to - store the thread ID. - - * dll.c (PthreadsEntryPoint): Implement. This is called - whenever a process loads the DLL. Used to initialise thread - local storage. - - * implement.h: Add ptw32_threadID_TlsIndex. - Add ()s around PTW32_VALID expression. - - * misc.c (pthread_self): Re-implement using Win32 TLS to store - the threads own ID. - -Wed Jul 29 11:39:03 1998 Ross Johnson - - * private.c: Corrections in comments. - (ptw32_new_thread): Alter "if" flow to be more natural. - - * cleanup.c (ptw32_handler_push): Same as below. - - * create.c (pthread_create): Same as below. - - * private.c (ptw32_new_thread): Rename "new" to "new_thread". - Since when has a C programmer been required to know C++? - -Tue Jul 28 14:04:29 1998 Ross Johnson - - * implement.h: Add PTW32_VALID macro. - - * sync.c (pthread_join): Modify to use the new thread - type and ptw32_delete_thread(). Rename "target" to "thread". - Remove extra local variable "target". - (pthread_detach): Ditto. - - * signal.c (pthread_sigmask): Move init of "us" out of inner block. - Fix instance of "this" should have been "us". Rename "us" to "thread". - - * sched.c (pthread_setschedparam): Modify to use the new thread - type. - (pthread_getschedparam): Ditto. - - * private.c (ptw32_find_thread): Fix return type and arg. - - * implement.h: Remove PTW32_YES and PTW32_NO. - (ptw32_new_thread): Add prototype. - (ptw32_find_thread): Ditto. - (ptw32_delete_thread): Ditto. - (ptw32_new_thread_entry): Remove prototype. - (ptw32_find_thread_entry): Ditto. - (ptw32_delete_thread_entry): Ditto. - ( PTW32_NEW, PTW32_INUSE, PTW32_EXITED, PTW32_REUSE): - Add. - - - * create.c (pthread_create): Minor rename "us" to "new" (I need - these cues but it doesn't stop me coming out with some major bugs - at times). - Load start_routine and arg into the thread so the wrapper can - call it. - - * exit.c (pthread_exit): Fix pthread_this should be pthread_self. - - * cancel.c (pthread_setcancelstate): Change - ptw32_threads_thread_t * to pthread_t and init with - pthread_this(). - (pthread_setcanceltype): Ditto. - - * exit.c (ptw32_exit): Add new pthread_t arg. - Rename ptw32_delete_thread_entry to ptw32_delete_thread. - Rename "us" to "thread". - (pthread_exit): Call ptw32_exit with added thread arg. - - * create.c (ptw32_start_call): Insert missing ")". - Add "us" arg to ptw32_exit() call. - (pthread_create): Modify to use new thread allocation scheme. - - * private.c: Added detailed explanation of the new thread - allocation scheme. - (ptw32_new_thread): Totally rewritten to use - new thread allocation scheme. - (ptw32_delete_thread): Ditto. - (ptw32_find_thread): Obsolete. - -Mon Jul 27 17:46:37 1998 Ross Johnson - - * create.c (pthread_create): Start of rewrite. Not completed yet. - - * private.c (ptw32_new_thread_entry): Start of rewrite. Not - complete. - - * implement.h (ptw32_threads_thread): Rename, remove thread - member, add win32handle and ptstatus members. - (ptw32_t): Add. - - * pthread.h: pthread_t is no longer mapped directly to a Win32 - HANDLE type. This is so we can let the Win32 thread terminate and - reuse the HANDLE while pthreads holds it's own thread ID until - the last waiting join exits. - -Mon Jul 27 00:20:37 1998 Ross Johnson - - * private.c (ptw32_delete_thread_entry): Destroy the thread - entry attribute object before deleting the thread entry itself. - - * attr.c (pthread_attr_init): Initialise cancel_pending = FALSE. - (pthread_attr_setdetachstate): Rename "detached" to "detachedstate". - (pthread_attr_getdetachstate): Ditto. - - * exit.c (ptw32_exit): Fix incorrect check for detachedstate. - - * implement.h (ptw32_call_t): Remove env member. - -Sun Jul 26 13:06:12 1998 Ross Johnson - - * implement.h (ptw32_new_thread_entry): Fix prototype. - (ptw32_find_thread_entry): Ditto. - (ptw32_delete_thread_entry): Ditto. - (ptw32_exit): Add prototype. - - * exit.c (ptw32_exit): New function. Called from pthread_exit() - and ptw32_start_call() to exit the thread. It allows an extra - argument which is the return code passed to _endthreadex(). - (ptw32_exit): Move thread entry delete call from ptw32_vacuum() - into here. Add more explanation of thread entry deletion. - (ptw32_exit): Clarify comment. - - * create.c (ptw32_start_call): Change pthread_exit() call to - ptw32_exit() call. - - * exit.c (ptw32_vacuum): Add thread entry deletion code - moved from ptw32_start_call(). See next item. - (pthread_exit): Remove longjmp(). Add mutex lock around thread table - manipulation code. This routine now calls _enthreadex(). - - * create.c (ptw32_start_call): Remove setjmp() call and move - cleanup code out. Call pthread_exit(NULL) to terminate the thread. - -1998-07-26 Ben Elliston - - * tsd.c (pthread_getspecific): Update comments. - - * mutex.c (pthread_mutexattr_setpshared): Not supported; remove. - (pthread_mutexattr_getpshared): Likewise. - - * pthread.h (pthread_mutexattr_setpshared): Remove prototype. - (pthread_mutexattr_getpshared): Likewise. - -Sun Jul 26 00:09:59 1998 Ross Johnson - - * sync.c: Rename all instances of ptw32_count_mutex to - ptw32_table_mutex. - - * implement.h: Rename ptw32_count_mutex to - ptw32_table_mutex. - - * global.c: Rename ptw32_count_mutex to - ptw32_table_mutex. - - * create.c (pthread_create): Add critical sections. - (ptw32_start_call): Rename ptw32_count_mutex to - ptw32_table_mutex. - - * cancel.c (pthread_setcancelstate): Fix indirection bug and rename - "this" to "us". - - * signal.c (pthread_sigmask): Rename "this" to "us" and fix some - minor syntax errors. Declare "us" and initialise it. - - * sync.c (pthread_detach): Rename "this" to "target". - - * pthread.h: Converting PTHREAD_* defines to alias the (const int) - values in global.c. - - * global.c: Started converting PTHREAD_* defines to (const int) as - a part of making the eventual pthreads DLL binary compatible - through version changes. - - * condvar.c (cond_wait): Add cancelation point. This applies the - point to both pthread_cond_wait() and pthread_cond_timedwait(). - - * exit.c (pthread_exit): Rename "this" to "us". - - * implement.h: Add comment. - - * sync.c (pthread_join): I've satisfied myself that pthread_detach() - does set the detached attribute in the thread entry attributes - to PTHREAD_CREATE_DETACHED. "if" conditions were changed to test - that attribute instead of a separate flag. - - * create.c (pthread_create): Rename "this" to "us". - (pthread_create): cancelstate and canceltype are not attributes - so the copy to thread entry attribute storage was removed. - Only the thread itself can change it's cancelstate or canceltype, - ie. the thread must exist already. - - * private.c (ptw32_delete_thread_entry): Mutex locks removed. - Mutexes must be applied at the caller level. - (ptw32_new_thread_entry): Ditto. - (ptw32_new_thread_entry): Init cancelstate, canceltype, and - cancel_pending to default values. - (ptw32_new_thread_entry): Rename "this" to "new". - (ptw32_find_thread_entry): Rename "this" to "entry". - (ptw32_delete_thread_entry): Rename "thread_entry" to "entry". - - * create.c (ptw32_start_call): Mutexes changed to - ptw32_count_mutex. All access to the threads table entries is - under the one mutex. Otherwise chaos reigns. - -Sat Jul 25 23:16:51 1998 Ross Johnson - - * implement.h (ptw32_threads_thread): Move cancelstate and - canceltype members out of pthread_attr_t into here. - - * fork.c (fork): Add comment. - -1998-07-25 Ben Elliston - - * fork.c (fork): Autoconfiscate. - -Sat Jul 25 00:00:13 1998 Ross Johnson - - * create.c (ptw32_start_call): Set thread priority. Ensure our - thread entry is removed from the thread table but only if - pthread_detach() was called and there are no waiting joins. - (pthread_create): Set detach flag in thread entry if the - thread is created PTHREAD_CREATE_DETACHED. - - * pthread.h (pthread_attr_t): Rename member "detachedstate". - - * attr.c (pthread_attr_init): Rename attr members. - - * exit.c (pthread_exit): Fix indirection mistake. - - * implement.h (PTW32_THREADS_TABLE_INDEX): Add. - - * exit.c (ptw32_vacuum): Fix incorrect args to - ptw32_handler_pop_all() calls. - Make thread entry removal conditional. - - * sync.c (pthread_join): Add multiple join and async detach handling. - - * implement.h (PTW32_THREADS_TABLE_INDEX): Add. - - * global.c (ptw32_threads_mutex_table): Add. - - * implement.h (ptw32_once_flag): Remove. - (ptw32_once_lock): Ditto. - (ptw32_threads_mutex_table): Add. - - * global.c (ptw32_once_flag): Remove. - (ptw32_once_lock): Ditto. - - * sync.c (pthread_join): Fix tests involving new return value - from ptw32_find_thread_entry(). - (pthread_detach): Ditto. - - * private.c (ptw32_find_thread_entry): Failure return code - changed from -1 to NULL. - -Fri Jul 24 23:09:33 1998 Ross Johnson - - * create.c (pthread_create): Change . to -> in sigmask memcpy() args. - - * pthread.h: (pthread_cancel): Add function prototype. - (pthread_testcancel): Ditto. - -1998-07-24 Ben Elliston - - * pthread.h (pthread_condattr_t): Rename dummy structure member. - (pthread_mutexattr_t): Likewise. - -Fri Jul 24 21:13:55 1998 Ross Johnson - - * cancel.c (pthread_cancel): Implement. - (pthread_testcancel): Implement. - - * exit.c (pthread_exit): Add comment explaining the longjmp(). - - * implement.h (ptw32_threads_thread_t): New member cancelthread. - (PTW32_YES): Define. - (PTW32_NO): Define. - (RND_SIZEOF): Remove. - - * create.c (pthread_create): Rename cancelability to cancelstate. - - * pthread.h (pthread_attr_t): Rename cancelability to cancelstate. - (PTHREAD_CANCELED): Define. - -1998-07-24 Ben Elliston - - * pthread.h (SIG_BLOCK): Define if not already defined. - (SIG_UNBLOCK): Likewise. - (SIG_SETMASK): Likewise. - (pthread_attr_t): Add signal mask member. - (pthread_sigmask): Add function prototype. - - * signal.c (pthread_sigmask): Implement. - - * create.c: #include to get a prototype for memcpy(). - (pthread_create): New threads inherit their creator's signal - mask. Copy the signal mask to the new thread structure if we know - about signals. - -Fri Jul 24 16:33:17 1998 Ross Johnson - - * fork.c (pthread_atfork): Add all the necessary push calls. - Local implementation semantics: - If we get an ENOMEM at any time then ALL handlers - (including those from previous pthread_atfork() calls) will be - popped off each of the three atfork stacks before we return. - (fork): Add all the necessary pop calls. Add the thread cancellation - and join calls to the child fork. - Add #includes. - - * implement.h: (ptw32_handler_push): Fix return type and stack arg - type in prototype. - (ptw32_handler_pop): Fix stack arg type in prototype. - (ptw32_handler_pop_all): Fix stack arg type in prototype. - - * cleanup.c (ptw32_handler_push): Change return type to int and - return ENOMEM if malloc() fails. - - * sync.c (pthread_detach): Use equality test, not assignment. - - * create.c (ptw32_start_call): Add call to Win32 CloseHandle() - if thread is detached. - -1998-07-24 Ben Elliston - - * sync.c (pthread_detach): Close the Win32 thread handle to - emulate detached (or daemon) threads. - -Fri Jul 24 03:00:25 1998 Ross Johnson - - * sync.c (pthread_join): Save valueptr arg in joinvalueptr for - pthread_exit() to use. - - * private.c (ptw32_new_thread_entry): Initialise joinvalueptr to - NULL. - - * create.c (ptw32_start_call): Rewrite to facilitate joins. - pthread_exit() will do a longjmp() back to here. Does appropriate - cleanup and exit/return from the thread. - (pthread_create): _beginthreadex() now passes a pointer to our - thread table entry instead of just the call member of that entry. - - * implement.h (ptw32_threads_thread): New member - void ** joinvalueptr. - (ptw32_call_t): New member jmpbuf env. - - * exit.c (pthread_exit): Major rewrite to handle joins and handing - value pointer to joining thread. Uses longjmp() back to - ptw32_start_call(). - - * create.c (pthread_create): Ensure values of new attribute members - are copied to the thread attribute object. - - * attr.c (pthread_attr_destroy): Fix merge conflicts. - (pthread_attr_getdetachstate): Fix merge conflicts. - (pthread_attr_setdetachstate): Fix merge conflicts. - - * pthread.h: Fix merge conflicts. - - * sync.c (pthread_join): Fix merge conflicts. - -Fri Jul 24 00:21:21 1998 Ross Johnson - - * sync.c (pthread_join): Add check for valid and joinable - thread. - (pthread_detach): Implement. After checking for a valid and joinable - thread, it's still a no-op. - - * private.c (ptw32_find_thread_entry): Bug prevented returning - an error value in some cases. - - * attr.c (pthread_attr_setdetachedstate): Implement. - (pthread_attr_getdetachedstate): Implement. - - * implement.h: Move more hidden definitions into here from - pthread.h. - -1998-07-24 Ben Elliston - - * pthread.h (PTHREAD_CREATE_JOINABLE): Define. - (PTHREAD_CREATE_DETACHED): Likewise. - (pthread_attr_t): Add new structure member `detached'. - (pthread_attr_getdetachstate): Add function prototype. - (pthread_attr_setdetachstate): Likewise. - - * sync.c (pthread_join): Return if the target thread is detached. - - * attr.c (pthread_attr_init): Initialise cancelability and - canceltype structure members. - (pthread_attr_getdetachstate): Implement. - (pthread_attr_setdetachstate): Likewise. - - * implement.h (PTW32_CANCEL_DEFAULTS): Remove. Bit fields - proved to be too cumbersome. Set the defaults in attr.c using the - public PTHREAD_CANCEL_* constants. - - * cancel.c: New file. - - * pthread.h (sched_param): Define this type. - (pthread_attr_getschedparam): Add function prototype. - (pthread_attr_setschedparam): Likewise. - (pthread_setcancelstate): Likewise. - (pthread_setcanceltype): Likewise. - (sched_get_priority_min): Likewise. - (sched_get_priority_max): Likewise. - (pthread_mutexattr_setprotocol): Remove; not supported. - (pthread_mutexattr_getprotocol): Likewise. - (pthread_mutexattr_setprioceiling): Likewise. - (pthread_mutexattr_getprioceiling): Likewise. - (pthread_attr_t): Add canceltype member. Update comments. - (SCHED_OTHER): Define this scheduling policy constant. - (SCHED_FIFO): Likewise. - (SCHED_RR): Likewise. - (SCHED_MIN): Define the lowest possible value for this constant. - (SCHED_MAX): Likewise, the maximum possible value. - (PTHREAD_CANCEL_ASYNCHRONOUS): Redefine. - (PTHREAD_CANCEL_DEFERRED): Likewise. - - * sched.c: New file. - (pthread_setschedparam): Implement. - (pthread_getschedparam): Implement. - (sched_get_priority_max): Validate policy argument. - (sched_get_priority_min): Likewise. - - * mutex.c (pthread_mutexattr_setprotocol): Remove; not supported. - (pthread_mutexattr_getprotocol): Likewise. - (pthread_mutexattr_setprioceiling): Likewise. - (pthread_mutexattr_getprioceiling): Likewise. - -Fri Jul 24 00:21:21 1998 Ross Johnson - - * create.c (pthread_create): Arg to ptw32_new_thread_entry() - changed. See next entry. Move mutex locks out. Changes made yesterday - and today allow us to start the new thread running rather than - temporarily suspended. - - * private.c (ptw32_new_thread_entry): ptw32_thread_table - was changed back to a table of thread structures rather than pointers. - As such we're trading storage for increaded speed. This routine - was modified to work with the new table. Mutex lock put in around - global data accesses. - (ptw32_find_thread_entry): Ditto - (ptw32_delete_thread_entry): Ditto - -Thu Jul 23 23:25:30 1998 Ross Johnson - - * global.c: New. Global data objects declared here. These moved from - pthread.h. - - * pthread.h: Move implementation hidden definitions into - implement.h. - - * implement.h: Move implementation hidden definitions from - pthread.h. Add constants to index into the different handler stacks. - - * cleanup.c (ptw32_handler_push): Simplify args. Restructure. - (ptw32_handler_pop): Simplify args. Restructure. - (ptw32_handler_pop_all): Simplify args. Restructure. - -Wed Jul 22 00:16:22 1998 Ross Johnson - - * attr.c, implement.h, pthread.h, ChangeLog: Resolve CVS merge - conflicts. - - * private.c (ptw32_find_thread_entry): Changes to return type - to support leaner ptw32_threads_table[] which now only stores - ptw32_thread_thread_t *. - (ptw32_new_thread_entry): Internal changes. - (ptw32_delete_thread_entry): Internal changes to avoid contention. - Calling routines changed accordingly. - - * pthread.h: Modified cleanup macros to use new generic push and pop. - Added destructor and atfork stacks to ptw32_threads_thread_t. - - * cleanup.c (ptw32_handler_push, ptw32_handler_pop, - ptw32_handler_pop_all): Renamed cleanup push and pop routines - and made generic to handle destructors and atfork handlers as - well. - - * create.c (ptw32_start_call): New function is a wrapper for - all new threads. It allows us to do some cleanup when the thread - returns, ie. that is otherwise only done if the thread is cancelled. - - * exit.c (ptw32_vacuum): New function contains code from - pthread_exit() that we need in the new ptw32_start_call() - as well. - - * implement.h: Various additions and minor changes. - - * pthread.h: Various additions and minor changes. - Change cleanup handler macros to use generic handler push and pop - functions. - - * attr.c: Minor mods to all functions. - (is_attr): Implemented missing function. - - * create.c (pthread_create): More clean up. - - * private.c (ptw32_find_thread_entry): Implement. - (ptw32_delete_thread_entry): Implement. - (ptw32_new_thread_entry): Implement. - These functions manipulate the implementations internal thread - table and are part of general code cleanup and modularisation. - They replace ptw32_getthreadindex() which was removed. - - * exit.c (pthread_exit): Changed to use the new code above. - - * pthread.h: Add cancelability constants. Update comments. - -1998-07-22 Ben Elliston - - * attr.c (pthread_setstacksize): Update test of attr argument. - (pthread_getstacksize): Likewise. - (pthread_setstackaddr): Likewise. - (pthread_getstackaddr): Likewise. - (pthread_attr_init): No need to allocate any storage. - (pthread_attr_destroy): No need to free any storage. - - * mutex.c (is_attr): Not likely to be needed; remove. - (remove_attr): Likewise. - (insert_attr): Likewise. - - * implement.h (ptw32_mutexattr_t): Moved to a public definition - in pthread.h. There was little gain in hiding these details. - (ptw32_condattr_t): Likewise. - (ptw32_attr_t): Likewise. - - * pthread.h (pthread_atfork): Add function prototype. - (pthread_attr_t): Moved here from implement.h. - - * fork.c (pthread_atfork): Preliminary implementation. - (ptw32_fork): Likewise. - -Wed Jul 22 00:16:22 1998 Ross Johnson - - * cleanup.c (ptw32_cleanup_push): Implement. - (ptw32_cleanup_pop): Implement. - (ptw32_do_cancellation): Implement. - These are private to the implementation. The real cleanup functions - are macros. See below. - - * pthread.h (pthread_cleanup_push): Implement as a macro. - (pthread_cleanup_pop): Implement as a macro. - Because these are macros which start and end a block, the POSIX scoping - requirement is observed. See the comment in the file. - - * exit.c (pthread_exit): Refine the code. - - * create.c (pthread_create): Code cleanup. - - * implement.h (RND_SIZEOF): Add RND_SIZEOF(T) to round sizeof(T) - up to multiple of DWORD. - Add function prototypes. - - * private.c (ptw32_getthreadindex): "*thread" should have been - "thread". Detect empty slot fail condition. - -1998-07-20 Ben Elliston - - * misc.c (pthread_once): Implement. Don't use a per-application - flag and mutex--make `pthread_once_t' contain these elements in - their structure. The earlier version had incorrect semantics. - - * pthread.h (ptw32_once_flag): Add new variable. Remove. - (ptw32_once_lock): Add new mutex lock to ensure integrity of - access to ptw32_once_flag. Remove. - (pthread_once): Add function prototype. - (pthread_once_t): Define this type. - -Mon Jul 20 02:31:05 1998 Ross Johnson - - * private.c (ptw32_getthreadindex): Implement. - - * pthread.h: Add application static data dependent on - _PTHREADS_BUILD_DLL define. This is needed to avoid allocating - non-sharable static data within the pthread DLL. - - * implement.h: Add ptw32_cleanup_stack_t, ptw32_cleanup_node_t - and PTW32_HASH_INDEX. - - * exit.c (pthread_exit): Begin work on cleanup and de-allocate - thread-private storage. - - * create.c (pthread_create): Add thread to thread table. - Keep a thread-private copy of the attributes with default values - filled in when necessary. Same for the cleanup stack. Make - pthread_create C run-time library friendly by using _beginthreadex() - instead of CreateThread(). Fix error returns. - -Sun Jul 19 16:26:23 1998 Ross Johnson - - * implement.h: Rename pthreads_thread_count to ptw32_threads_count. - Create ptw32_threads_thread_t struct to keep thread specific data. - - * create.c: Rename pthreads_thread_count to ptw32_threads_count. - (pthread_create): Handle errors from CreateThread(). - -1998-07-19 Ben Elliston - - * condvar.c (pthread_cond_wait): Generalise. Moved from here .. - (cond_wait): To here. - (pthread_cond_timedwait): Implement; use generalised cond_wait(). - - * pthread.h (pthread_key_t): Define this type. - (pthread_key_create): Add function prototype. - (pthread_setspecific): Likewise. - (pthread_getspecific): Likwise. - (pthread_key_delete): Likewise. - - * tsd.c (pthread_key_create): Implement. - (pthread_setspecific): Likewise. - (pthread_getspecific): Likewise. - (pthread_key_delete): Likewise. - - * mutex.c (pthread_mutex_trylock): Return ENOSYS if this function - is called on a Win32 platform which is not Windows NT. - -1998-07-18 Ben Elliston - - * condvar.c (pthread_condattr_init): Do not attempt to malloc any - storage; none is needed now that condattr_t is an empty struct. - (pthread_condattr_destory): Likewise; do not free storage. - (pthread_condattr_setpshared): No longer supported; return ENOSYS. - (pthread_condattr_getpshared): Likewise. - (pthread_cond_init): Implement with help from Douglas Schmidt. - Remember to initialise the cv's internal mutex. - (pthread_cond_wait): Likewise. - (pthread_cond_signal): Likewise. - (pthread_cond_broadcast): Likewise. - (pthread_cond_timedwait): Preliminary implementation, but I need - to see some API documentation for `WaitForMultipleObject'. - (pthread_destory): Implement. - - * pthread.h (pthread_cond_init): Add function protoype. - (pthread_cond_broadcast): Likewise. - (pthread_cond_signal): Likewise. - (pthread_cond_timedwait): Likewise. - (pthread_cond_wait): Likewise. - (pthread_cond_destroy): Likewise. - (pthread_cond_t): Define this type. Fix for u_int. Do not assume - that the mutex contained withing the pthread_cond_t structure will - be a critical section. Use our new POSIX type! - - * implement.h (ptw32_condattr_t): Remove shared attribute. - -1998-07-17 Ben Elliston - - * pthread.h (PTHREADS_PROCESS_PRIVATE): Remove. - (PTHREAD_PROCESS_SHARED): Likewise. No support for mutexes shared - across processes for now. - (pthread_mutex_t): Use a Win32 CRITICAL_SECTION type for better - performance. - - * implement.h (ptw32_mutexattr_t): Remove shared attribute. - - * mutex.c (pthread_mutexattr_setpshared): This optional function - is no longer supported, since we want to implement POSIX mutex - variables using the much more efficient Win32 critical section - primitives. Critical section objects in Win32 cannot be shared - between processes. - (pthread_mutexattr_getpshared): Likewise. - (pthread_mutexattr_init): No need to malloc any storage; the - attributes structure is now empty. - (pthread_mutexattr_destroy): This is now a nop. - (pthread_mutex_init): Use InitializeCriticalSection(). - (pthread_mutex_destroy): Use DeleteCriticalSection(). - (pthread_mutex_lock): Use EnterCriticalSection(). - (pthread_mutex_trylock): Use TryEnterCriticalSection(). This is - not supported by Windows 9x, but trylock is a hack anyway, IMHO. - (pthread_mutex_unlock): Use LeaveCriticalSection(). - -1998-07-14 Ben Elliston - - * attr.c (pthread_attr_setstacksize): Implement. - (pthread_attr_getstacksize): Likewise. - (pthread_attr_setstackaddr): Likewise. - (pthread_attr_getstackaddr): Likewise. - (pthread_attr_init): Likewise. - (pthread_attr_destroy): Likewise. - - * condvar.c (pthread_condattr_init): Add `_cond' to function name. - - * mutex.c (pthread_mutex_lock): Add `_mutex' to function name. - (pthread_mutex_trylock): Likewise. - (pthread_mutex_unlock): Likewise. - - * pthread.h (pthread_condattr_setpshared): Fix typo. - (pthread_attr_init): Add function prototype. - (pthread_attr_destroy): Likewise. - (pthread_attr_setstacksize): Likewise. - (pthread_attr_getstacksize): Likewise. - (pthread_attr_setstackaddr): Likewise. - (pthread_attr_getstackaddr): Likewise. - -Mon Jul 13 01:09:55 1998 Ross Johnson - - * implement.h: Wrap in #ifndef _IMPLEMENT_H - - * create.c (pthread_create): Map stacksize attr to Win32. - - * mutex.c: Include implement.h - -1998-07-13 Ben Elliston - - * condvar.c (pthread_condattr_init): Implement. - (pthread_condattr_destroy): Likewise. - (pthread_condattr_setpshared): Likewise. - (pthread_condattr_getpshared): Likewise. - - * implement.h (PTHREAD_THREADS_MAX): Remove trailing semicolon. - (PTHREAD_STACK_MIN): Specify; needs confirming. - (ptw32_attr_t): Define this type. - (ptw32_condattr_t): Likewise. - - * pthread.h (pthread_mutex_t): Define this type. - (pthread_condattr_t): Likewise. - (pthread_mutex_destroy): Add function prototype. - (pthread_lock): Likewise. - (pthread_trylock): Likewise. - (pthread_unlock): Likewise. - (pthread_condattr_init): Likewise. - (pthread_condattr_destroy): Likewise. - (pthread_condattr_setpshared): Likewise. - (pthread_condattr_getpshared): Likewise. - - * mutex.c (pthread_mutex_init): Implement. - (pthread_mutex_destroy): Likewise. - (pthread_lock): Likewise. - (pthread_trylock): Likewise. - (pthread_unlock): Likewise. - -1998-07-12 Ben Elliston - - * implement.h (ptw32_mutexattr_t): Define this implementation - internal type. Application programmers only see a mutex attribute - object as a void pointer. - - * pthread.h (pthread_mutexattr_t): Define this type. - (pthread_mutexattr_init): Add function prototype. - (pthread_mutexattr_destroy): Likewise. - (pthread_mutexattr_setpshared): Likewise. - (pthread_mutexattr_getpshared): Likewise. - (pthread_mutexattr_setprotocol): Likewise. - (pthread_mutexattr_getprotocol): Likewise. - (pthread_mutexattr_setprioceiling): Likewise. - (pthread_mutexattr_getprioceiling): Likewise. - (PTHREAD_PROCESS_PRIVATE): Define. - (PTHREAD_PROCESS_SHARED): Define. - - * mutex.c (pthread_mutexattr_init): Implement. - (pthread_mutexattr_destroy): Implement. - (pthread_mutexattr_setprotocol): Implement. - (pthread_mutexattr_getprotocol): Likewise. - (pthread_mutexattr_setprioceiling): Likewise. - (pthread_mutexattr_getprioceiling): Likewise. - (pthread_mutexattr_setpshared): Likewise. - (pthread_mutexattr_getpshared): Likewise. - (insert_attr): New function; very preliminary implementation! - (is_attr): Likewise. - (remove_attr): Likewise. - -Sat Jul 11 14:48:54 1998 Ross Johnson - - * implement.h: Preliminary implementation specific defines. - - * create.c (pthread_create): Preliminary implementation. - -1998-07-11 Ben Elliston - - * sync.c (pthread_join): Implement. - - * misc.c (pthread_equal): Likewise. - - * pthread.h (pthread_join): Add function prototype. - (pthread_equal): Likewise. - -1998-07-10 Ben Elliston - - * misc.c (pthread_self): Implement. - - * exit.c (pthread_exit): Implement. - - * pthread.h (pthread_exit): Add function prototype. - (pthread_self): Likewise. - (pthread_t): Define this type. - -1998-07-09 Ben Elliston - - * create.c (pthread_create): A dummy stub right now. - - * pthread.h (pthread_create): Add function prototype. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/FAQ b/bridge/third_party/quickjs/compat/win32/pthreads/FAQ deleted file mode 100644 index cb1786c5ae..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/FAQ +++ /dev/null @@ -1,451 +0,0 @@ - ========================================= - PTHREADS-WIN32 Frequently Asked Questions - ========================================= - -INDEX ------ - -Q 1 What is it? - -Q 2 Which of the several dll versions do I use? - or, - What are all these pthread*.dll and pthread*.lib files? - -Q 3 What is the library naming convention? - -Q 4 Cleanup code default style or: it used to work when I built - the library myself, but now it doesn't - why? - -Q 5 Why is the default library version now less exception-friendly? - -Q 6 Should I use Cygwin or Mingw32 as a development environment? - -Q 7 Now that pthreads-win32 builds under Mingw32, why do I get - memory access violations (segfaults)? - -Q 8 How do I use pthread.dll for Win32 (Visual C++ 5.0) - -Q 9 Cancelation doesn't work for me, why? - -Q 10 How do I generate pthreadGCE.dll and libpthreadw32.a for use - with Mingw32? - -Q 11 Why isn't pthread_t defined as a scalar (e.g. pointer or int) - like it is for other POSIX threads implementations? - -============================================================================= - -Q 1 What is it? ---- - -Pthreads-win32 is an Open Source Software implementation of the -Threads component of the POSIX 1003.1c 1995 Standard for Microsoft's -Win32 environment. Some functions from POSIX 1003.1b are also -supported including semaphores. Other related functions include -the set of read-write lock functions. The library also supports -some of the functionality of the Open Group's Single Unix -specification, version 2, namely mutex types. - -See the file "ANNOUNCE" for more information including standards -conformance details and list of supported routines. - - ------------------------------------------------------------------------------- - -Q 2 Which of the several dll versions do I use? ---- or, - What are all these pthread*.dll and pthread*.lib files? - -Simply, you only use one of them, but you need to choose carefully. - -The most important choice you need to make is whether to use a -version that uses exceptions internally, or not (there are versions -of the library that use exceptions as part of the thread -cancelation and cleanup implementation, and one that uses -setjmp/longjmp instead). - -There is some contension amongst POSIX threads experts as -to how POSIX threads cancelation and exit should work -with languages that include exceptions and handlers, e.g. -C++ and even C (Microsoft's Structured Exceptions). - -The issue is: should cancelation of a thread in, say, -a C++ application cause object destructors and C++ exception -handlers to be invoked as the stack unwinds during thread -exit, or not? - -There seems to be more opinion in favour of using the -standard C version of the library (no EH) with C++ applications -since this appears to be the assumption commercial pthreads -implementations make. Therefore, if you use an EH version -of pthreads-win32 then you may be under the illusion that -your application will be portable, when in fact it is likely to -behave very differently linked with other pthreads libraries. - -Now you may be asking: why have you kept the EH versions of -the library? - -There are a couple of reasons: -- there is division amongst the experts and so the code may - be needed in the future. (Yes, it's in the repository and we - can get it out anytime in the future, but ...) -- pthreads-win32 is one of the few implementations, and possibly - the only freely available one, that has EH versions. It may be - useful to people who want to play with or study application - behaviour under these conditions. - - ------------------------------------------------------------------------------- - -Q 3 What is the library naming convention? ---- - -Because the library is being built using various exception -handling schemes and compilers - and because the library -may not work reliably if these are mixed in an application, -each different version of the library has it's own name. - -Note 1: the incompatibility is really between EH implementations -of the different compilers. It should be possible to use the -standard C version from either compiler with C++ applications -built with a different compiler. If you use an EH version of -the library, then you must use the same compiler for the -application. This is another complication and dependency that -can be avoided by using only the standard C library version. - -Note 2: if you use a standard C pthread*.dll with a C++ -application, then any functions that you define that are -intended to be called via pthread_cleanup_push() must be -__cdecl. - -Note 3: the intention is to also name either the VC or GC -version (it should be arbitrary) as pthread.dll, including -pthread.lib and libpthread.a as appropriate. - -In general: - pthread[VG]{SE,CE,C}.dll - pthread[VG]{SE,CE,C}.lib - -where: - [VG] indicates the compiler - V - MS VC - G - GNU C - - {SE,CE,C} indicates the exception handling scheme - SE - Structured EH - CE - C++ EH - C - no exceptions - uses setjmp/longjmp - -For example: - pthreadVSE.dll (MSVC/SEH) - pthreadGCE.dll (GNUC/C++ EH) - pthreadGC.dll (GNUC/not dependent on exceptions) - -The GNU library archive file names have changed to: - - libpthreadGCE.a - libpthreadGC.a - - ------------------------------------------------------------------------------- - -Q 4 Cleanup code default style or: it used to work when I built ---- the library myself, but now it doesn't - why? - -Up to and including snapshot 2001-07-12, if not defined, the cleanup -style was determined automatically from the compiler used, and one -of the following was defined accordingly: - - __CLEANUP_SEH MSVC only - __CLEANUP_CXX C++, including MSVC++, GNU G++ - __CLEANUP_C C, including GNU GCC, not MSVC - -These defines determine the style of cleanup (see pthread.h) and, -most importantly, the way that cancelation and thread exit (via -pthread_exit) is performed (see the routine ptw32_throw() in private.c). - -In short, the exceptions versions of the library throw an exception -when a thread is canceled or exits (via pthread_exit()), which is -caught by a handler in the thread startup routine, so that the -the correct stack unwinding occurs regardless of where the thread -is when it's canceled or exits via pthread_exit(). - -After snapshot 2001-07-12, unless your build explicitly defines (e.g. -via a compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then -the build now ALWAYS defaults to __CLEANUP_C style cleanup. This style -uses setjmp/longjmp in the cancelation and pthread_exit implementations, -and therefore won't do stack unwinding even when linked to applications -that have it (e.g. C++ apps). This is for consistency with most/all -commercial Unix POSIX threads implementations. - -Although it was not clearly documented before, it is still necessary to -build your application using the same __CLEANUP_* define as was -used for the version of the library that you link with, so that the -correct parts of pthread.h are included. That is, the possible -defines require the following library versions: - - __CLEANUP_SEH pthreadVSE.dll - __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll - __CLEANUP_C pthreadVC.dll or pthreadGC.dll - -THE POINT OF ALL THIS IS: if you have not been defining one of these -explicitly, then the defaults have been set according to the compiler -and language you are using, as described at the top of this -section. - -THIS NOW CHANGES, as has been explained above. For example: - -If you were building your application with MSVC++ i.e. using C++ -exceptions (rather than SEH) and not explicitly defining one of -__CLEANUP_*, then __CLEANUP_C++ was defined for you in pthread.h. -You should have been linking with pthreadVCE.dll, which does -stack unwinding. - -If you now build your application as you had before, pthread.h will now -set __CLEANUP_C as the default style, and you will need to link -with pthreadVC.dll. Stack unwinding will now NOT occur when a -thread is canceled, nor when the thread calls pthread_exit(). - -Your application will now most likely behave differently to previous -versions, and in non-obvious ways. Most likely is that local -objects may not be destroyed or cleaned up after a thread -is canceled. - -If you want the same behaviour as before, then you must now define -__CLEANUP_C++ explicitly using a compiler option and link with -pthreadVCE.dll as you did before. - - ------------------------------------------------------------------------------- - -Q 5 Why is the default library version now less exception-friendly? ---- - -Because most commercial Unix POSIX threads implementations don't allow you to -choose to have stack unwinding. (Compaq's TRU64 Unix is possibly an exception.) - -Therefore, providing it in pthread-win32 as a default could be dangerous -and non-portable. We still provide the choice but you must now consciously -make it. - -WHY NOT REMOVE THE EXCEPTIONS VERSIONS OF THE LIBRARY ALTOGETHER? -There are a few reasons: -- because there are well respected POSIX threads people who believe - that POSIX threads implementations should be exceptions-aware and - do the expected thing in that context. (There are equally respected - people who believe it should not be easily accessible, if it's there - at all.) -- because pthreads-win32 is one of the few implementations that has - the choice, perhaps the only freely available one, and so offers - a laboratory to people who may want to explore the effects; -- although the code will always be around somewhere for anyone who - wants it, once it's removed from the current version it will not be - nearly as visible to people who may have a use for it. - - ------------------------------------------------------------------------------- - -Q 6 Should I use Cygwin or Mingw32 as a development environment? ---- - -Important: see Q7 also. - -Use Mingw32 with the MSVCRT library to build applications that use -the pthreads DLL. - -Cygwin's own internal support for POSIX threads is growing. -Consult that project's documentation for more information. - ------------------------------------------------------------------------------- - -Q 7 Now that pthreads-win32 builds under Mingw32, why do I get ---- memory access violations (segfaults)? - -The latest Mingw32 package has thread-safe exception handling (see Q10). -Also, see Q6 above. - ------------------------------------------------------------------------------- - -Q 8 How do I use pthread.dll for Win32 (Visual C++ 5.0) ---- - -> -> I'm a "rookie" when it comes to your pthread implementation. I'm currently -> desperately trying to install the prebuilt .dll file into my MSVC compiler. -> Could you please provide me with explicit instructions on how to do this (or -> direct me to a resource(s) where I can acquire such information)? -> -> Thank you, -> - -You should have a .dll, .lib, .def, and three .h files. It is recommended -that you use pthreadVC.dll, rather than pthreadVCE.dll or pthreadVSE.dll -(see Q2 above). - -The .dll can go in any directory listed in your PATH environment -variable, so putting it into C:\WINDOWS should work. - -The .lib file can go in any directory listed in your LIB environment -variable. - -The .h files can go in any directory listed in your INCLUDE -environment variable. - -Or you might prefer to put the .lib and .h files into a new directory -and add its path to LIB and INCLUDE. You can probably do this easiest -by editing the file:- - -C:\Program Files\DevStudio\vc\bin\vcvars32.bat - -The .def file isn't used by anything in the pre-compiled version but -is included for information. - -Cheers. -Ross - ------------------------------------------------------------------------------- - -Q 9 Cancelation doesn't work for me, why? ---- - -> I'm investigating a problem regarding thread cancelation. The thread I want -> to cancel has PTHREAD_CANCEL_ASYNCHRONOUS, however, this piece of code -> blocks on the join(): -> -> if ((retv = Pthread_cancel( recvThread )) == 0) -> { -> retv = Pthread_join( recvThread, 0 ); -> } -> -> Pthread_* are just macro's; they call pthread_*. -> -> The thread recvThread seems to block on a select() call. It doesn't get -> cancelled. -> -> Two questions: -> -> 1) is this normal behaviour? -> -> 2) if not, how does the cancel mechanism work? I'm not very familliar to -> win32 programming, so I don't really understand how the *Event() family of -> calls work. - -The answer to your first question is, normal POSIX behaviour would -be to asynchronously cancel the thread. However, even that doesn't -guarantee cancelation as the standard only says it should be -cancelled as soon as possible. - -Snapshot 99-11-02 or earlier only partially supports asynchronous cancellation. -Snapshots since then simulate async cancelation by poking the address of -a cancelation routine into the PC of the threads context. This requires -the thread to be resumed in some way for the cancelation to actually -proceed. This is not true async cancelation, but it is as close as we've -been able to get to it. - -If the thread you're trying to cancel is blocked (for instance, it could be -waiting for data from the network), it will only get cancelled when it unblocks -(when the data arrives). For true pre-emptive cancelation in these cases, -pthreads-win32 from snapshot 2004-05-16 can automatically recognise and use the -QueueUserAPCEx package by Panagiotis E. Hadjidoukas. This package is available -from the pthreads-win32 ftp site and is included in the pthreads-win32 -self-unpacking zip from 2004-05-16 onwards. - -Using deferred cancelation would normally be the way to go, however, -even though the POSIX threads standard lists a number of C library -functions that are defined as deferred cancelation points, there is -no hookup between those which are provided by Windows and the -pthreads-win32 library. - -Incidently, it's worth noting for code portability that the older POSIX -threads standards cancelation point lists didn't include "select" because -(as I read in Butenhof) it wasn't part of POSIX. However, it does appear in -the SUSV3. - -Effectively, the only mandatory cancelation points that pthreads-win32 -recognises are those the library implements itself, ie. - - pthread_testcancel - pthread_cond_wait - pthread_cond_timedwait - pthread_join - sem_wait - sem_timedwait - pthread_delay_np - -The following routines from the non-mandatory list in SUSV3 are -cancelation points in pthreads-win32: - - pthread_rwlock_wrlock - pthread_rwlock_timedwrlock - -The following routines from the non-mandatory list in SUSV3 are not -cancelation points in pthreads-win32: - - pthread_rwlock_rdlock - pthread_rwlock_timedrdlock - -Pthreads-win32 also provides two functions that allow you to create -cancelation points within your application, but only for cases where -a thread is going to block on a Win32 handle. These are: - - pthreadCancelableWait(HANDLE waitHandle) /* Infinite wait */ - - pthreadCancelableTimedWait(HANDLE waitHandle, DWORD timeout) - ------------------------------------------------------------------------------- - - -Q 10 How do I create thread-safe applications using ----- pthreadGCE.dll, libpthreadw32.a and Mingw32? - -This should not be a problem with recent versions of MinGW32. - -For early versions, see Thomas Pfaff's email at: -http://sources.redhat.com/ml/pthreads-win32/2002/msg00000.html ------------------------------------------------------------------------------- - -Q 11 Why isn't pthread_t defined as a scalar (e.g. pointer or int) - like it is for other POSIX threads implementations? ----- - -Originally pthread_t was defined as a pointer (to the opaque pthread_t_ -struct) and later it was changed to a struct containing the original -pointer plus a sequence counter. This is allowed under both the original -POSIX Threads Standard and the current Single Unix Specification. - -When pthread_t is a simple pointer to a struct some very difficult to -debug problems arise from the process of freeing and later allocing -thread structs because new pthread_t handles can acquire the identity of -previously detached threads. The change to a struct was made, along with -some changes to their internal managment, in order to guarantee (for -practical applications) that the pthread_t handle will be unique over the -life of the running process. - -Where application code attempts to compare one pthread_t against another -directly, a compiler error will be emitted because structs can't be -compared at that level. This should signal a potentially serious problem -in the code design, which would go undetected if pthread_t was a scalar. - -The POSIX Threading API provides a function named pthread_equal() to -compare pthread_t thread handles. - -Other pthreads implementations, such as Sun's, use an int as the handle -but do guarantee uniqueness within the process scope. Win32 scalar typed -thread handles also guarantee uniqueness in system scope. It wasn't clear -how well the internal management of these handles would scale as the -number of threads and the fragmentation of the sequence numbering -increased for applications where thousands or millions of threads are -created and detached over time. The current management of threads within -pthreads-win32 using structs for pthread_t, and reusing without ever -freeing them, reduces the management time overheads to a constant, which -could be important given that pthreads-win32 threads are built on top of -Win32 threads and will therefore include that management overhead on top -of their own. The cost is that the memory resources used for thread -handles will remain at the peak level until the process exits. - -While it may be inconvenient for developers to be forced away from making -assumptions about the internals of pthread_t, the advantage for the -future development of pthread-win32, as well as those applications that -use it and other pthread implementations, is that the library is free to -change pthread_t internals and management as better methods arise. - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/MAINTAINERS b/bridge/third_party/quickjs/compat/win32/pthreads/MAINTAINERS deleted file mode 100644 index d253c1f69e..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/MAINTAINERS +++ /dev/null @@ -1,4 +0,0 @@ -CVS Repository maintainers - -Ross Johnson rpj@ise.canberra.edu.au -Ben Elliston bje@cygnus.com diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/NEWS b/bridge/third_party/quickjs/compat/win32/pthreads/NEWS deleted file mode 100644 index d1b789635f..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/NEWS +++ /dev/null @@ -1,1241 +0,0 @@ -RELEASE 2.9.0 -------------- -(2012-05-25) - -General -------- -New bug fixes in this release since 2.8.0 have NOT been applied to the -1.x.x series. - -Some changes post 2011-02-26 in CVS may not be compatible with pre -Windows 2000 systems. - -Use of other than the "C" version of the library is now discouraged. -That is, the "C++" version fails some tests and does not provide any -additional functionality. - -Testing and verification ------------------------- -This version has been tested on SMP architecture (Intel x64 Hex Core) -by completing the included test suite, stress and bench tests. - -New Features ------------- -DLL properties now properly includes the target architecture, i.e. -right-click on the file pthreadVC2.dll in explorer and choose the Detail -tab will show the compiler and architecture in the description field, e.g. -"MS C x64" or "MS C x86". -- Ross Johnson - -(MSC and GNU builds) The statically linked library now automatically -initialises and cleans up on program start/exit, i.e. statically linked -applications need not call the routines pthread_win32_process_attach_np() -and pthread_win32_process_detach_np() explicitly. The per-thread routine -pthread_win32_thread_detach_np() is also called at program exit to cleanup -POSIX resources acquired by the primary Windows native thread, if I (RJ) -understand the process correctly. Other Windows native threads that call -POSIX API routines may need to call the thread detach routine on thread -exit if the application depends on reclaimed POSIX resources or running -POSIX TSD (TLS) destructors. -See README.NONPORTABLE for descriptions of these routines. -- Ramiro Polla - -Robust mutexes are implemented within the PROCESS_PRIVATE scope. NOTE that -pthread_mutex_* functions may return different error codes for robust -mutexes than they otherwise do in normal usage, e.g. pthread_mutex_unlock -is required to check ownership for all mutex types when the mutex is -robust, whereas this does not occur for the "normal" non-robust mutex type. -- Ross Johnson - -pthread_getunique_np is implemented for source level compatibility -with some other implementations. This routine returns a 64 bit -sequence number that is uniquely associated with a thread. It can be -used by applications to order or hash POSIX thread handles. -- Ross Johnson - -Bug fixes ---------- -Many more changes for 64 bit systems. -- Kai Tietz - -Various modifications and fixes to build and test for WinCE. -- Marcel Ruff, Sinan Kaya - -Fix pthread_cond_destroy() - should not be a cancellation point. Other -minor build problems fixed. -- Romano Paolo Tenca - -Remove potential deadlock condition from pthread_cond_destroy(). -- Eric Berge - -Various modifications to build and test for Win64. -- Kip Streithorst - -Various fixes to the QueueUserAPCEx async cancellation helper DLL -(this is a separate download) and pthreads code cleanups. -- Sebastian Gottschalk - -Removed potential NULL pointer reference. -- Robert Kindred - -Removed the requirement that applications restrict the number of threads -calling pthread_barrier_wait to just the barrier count. Also reduced the -contention between barrier_wait and barrier_destroy. This change will have -slowed barriers down slightly but halves the number of semaphores consumed -per barrier to one. -- Ross Johnson - -Fixed a handle leak in sched_[gs]etscheduler. -- Mark Pizzolato - -Removed all of the POSIX re-entrant function compatibility macros from pthread.h. -Some were simply not semanticly correct. -- Igor Lubashev - -Threads no longer attempt to pass uncaught exceptions out of thread scope (C++ -and SEH builds only). Uncaught exceptions now cause the thread to exit with -the return code PTHREAD_CANCELED. -- Ross Johnson - -Lots of casting fixes particularly for x64, Interlocked fixes and reworking -for x64. -- Daniel Richard G., John Kamp - -Other changes -------------- -Dependence on the winsock library is now discretionary via -#define RETAIN_WSALASTERROR in config.h. It is undefined by default unless -WINCE is defined (because RJ is unsure of the dependency there). -- Ramiro Polla - -Several static POSIX mutexes used for internal management were replaced by -MCS queue-based locks to reduce resource consumption, in particular use of Win32 -objects. -- Ross Johnson - -For security, the QuserEx.dll if used must now be installed in the Windows System -folder. -- Ross Johnson - -New tests ---------- -robust[1-5].c - Robust mutexes -sequence1.c - per-thread unique sequence numbers - -Modified tests and benchtests ------------------------------ -All mutex*.c tests wherever appropriate have been modified to also test -robust mutexes under the same conditions. -Added robust mutex benchtests to benchtest*.c wherever appropriate. - - -RELEASE 2.8.0 -------------- -(2006-12-22) - -General -------- -New bug fixes in this release since 2.7.0 have not been applied to the -version 1.x.x series. It is probably time to drop version 1. - -Testing and verification ------------------------- -This release has not yet been tested on SMP architechtures. All tests pass -on a uni-processor system. - -Bug fixes ---------- -Sem_destroy could return EBUSY even though no threads were waiting on the -semaphore. Other races around invalidating semaphore structs (internally) -have been removed as well. - -New tests ---------- -semaphore5.c - tests the bug fix referred to above. - - -RELEASE 2.7.0 -------------- -(2005-06-04) - -General -------- -All new features in this release have been back-ported in release 1.11.0, -including the incorporation of MCS locks in pthread_once, however, versions -1 and 2 remain incompatible even though they are now identical in -performance and functionality. - -Testing and verification ------------------------- -This release has been tested (passed the test suite) on both uni-processor -and multi-processor systems. -- Tim Theisen - -Bug fixes ---------- -Pthread_once has been re-implemented to remove priority boosting and other -complexity to improve robustness. Races for Win32 handles that are not -recycle-unique have been removed. The general form of pthread_once is now -the same as that suggested earlier by Alexander Terekhov, but instead of the -'named mutex', a queue-based lock has been implemented which has the required -properties of dynamic self initialisation and destruction. This lock is also -efficient. The ABI is unaffected in as much as the size of pthread_once_t has -not changed and PTHREAD_ONCE_INIT has not changed, however, applications that -peek inside pthread_once_t, which is supposed to be opaque, will break. -- Vladimir Kliatchko - -New features ------------- -* Support for Mingw cross development tools added to GNUmakefile. -Mingw cross tools allow building the libraries on Linux. -- Mikael Magnusson - - -RELEASE 2.6.0 -------------- -(2005-05-19) - -General -------- -All of the bug fixes and new features in this release have been -back-ported in release 1.10.0. - -Testing and verification ------------------------- -This release has been tested (passed the test suite) on both uni-processor -and multi-processor systems. Thanks to Tim Theisen at TomoTherapy for -exhaustively running the MP tests and for providing crutial observations -and data when faults are detected. - -Bugs fixed ----------- - -* pthread_detach() now reclaims remaining thread resources if called after -the target thread has terminated. Previously, this routine did nothing in -this case. - -New tests ---------- - -* detach1.c - tests that pthread_detach properly invalidates the target -thread, which indicates that the thread resources have been reclaimed. - - -RELEASE 2.5.0 -------------- -(2005-05-09) - -General -------- - -The package now includes a reference documentation set consisting of -HTML formatted Unix-style manual pages that have been edited for -consistency with Pthreads-w32. The set can also be read online at: -http://sources.redhat.com/pthreads-win32/manual/index.html - -Thanks again to Tim Theisen for running the test suite pre-release -on an MP system. - -All of the bug fixes and new features in this release have been -back-ported in release 1.9.0. - -Bugs fixed ----------- - -* Thread Specific Data (TSD) key management has been ammended to -eliminate a source of (what was effectively) resource leakage (a HANDLE -plus memory for each key destruct routine/thread association). This was -not a true leak because these resources were eventually reclaimed when -pthread_key_delete was run AND each thread referencing the key had exited. -The problem was that these two conditions are often not met until very -late, and often not until the process is about to exit. - -The ammended implementation avoids the need for the problematic HANDLE -and reclaims the memory as soon as either the key is deleted OR the -thread exits, whichever is first. - -Thanks to Richard Hughes at Aculab for identifying and locating the leak. - -* TSD key destructors are now processed up to PTHREAD_DESTRUCTOR_ITERATIONS -times instead of just once. PTHREAD_DESTRUCTOR_ITERATIONS has been -defined in pthread.h for some time but not used. - -* Fix a semaphore accounting race between sem_post/sem_post_multiple -and sem_wait cancellation. This is the same issue as with -sem_timedwait that was fixed in the last release. - -* sem_init, sem_post, and sem_post_multiple now check that the -semaphore count never exceeds _POSIX_SEM_VALUE_MAX. - -* Although sigwait() is nothing more than a no-op, it should at least -be a cancellation point to be consistent with the standard. - -New tests ---------- - -* stress1.c - attempts to expose problems in condition variable -and semaphore timed wait logic. This test was inspired by Stephan -Mueller's sample test code used to identify the sem_timedwait bug -from the last release. It's not a part of the regular test suite -because it can take awhile to run. To run it: -nmake clean VC-stress - -* tsd2.c - tests that key destructors are re-run if the tsd key value is -not NULL after the destructor routine has run. Also tests that -pthread_setspecific() and pthread_getspecific() are callable from -destructors. - - -RELEASE 2.4.0 -------------- -(2005-04-26) - -General -------- - -There is now no plan to release a version 3.0.0 to fix problems in -pthread_once(). Other possible implementations of pthread_once -will still be investigated for a possible future release in an attempt -to reduce the current implementation's complexity. - -All of the bug fixes and new features in this release have been -back-ported for release 1.8.0. - -Bugs fixed ----------- - -* Fixed pthread_once race (failures on an MP system). Thanks to -Tim Theisen for running exhaustive pre-release testing on his MP system -using a range of compilers: - VC++ 6 - VC++ 7.1 - Intel C++ version 8.0 -All tests passed. -Some minor speed improvements were also done. - -* Fix integer overrun error in pthread_mutex_timedlock() - missed when -sem_timedwait() was fixed in release 2.2.0. This routine no longer returns -ENOTSUP when NEED_SEM is defined - it is supported (NEED_SEM is only -required for WinCE versions prior to 3.0). - -* Fix timeout bug in sem_timedwait(). -- Thanks to Stephan Mueller for reporting, providing diagnostic output -and test code. - -* Fix several problems in the NEED_SEM conditionally included code. -NEED_SEM included code is provided for systems that don't implement W32 -semaphores, such as WinCE prior to version 3.0. An alternate implementation -of POSIX semaphores is built using W32 events for these systems when -NEED_SEM is defined. This code has been completely rewritten in this -release to reuse most of the default POSIX semaphore code, and particularly, -to implement all of the sem_* routines supported by pthreads-win32. Tim -Theisen also run the test suite over the NEED_SEM code on his MP system. All -tests passed. - -* The library now builds without errors for the Borland Builder 5.5 compiler. - -New features ------------- - -* pthread_mutex_timedlock() and all sem_* routines provided by -pthreads-win32 are now implemented for WinCE versions prior to 3.0. Those -versions did not implement W32 semaphores. Define NEED_SEM in config.h when -building the library for these systems. - -Known issues in this release ----------------------------- - -* pthread_once is too complicated - but it works as far as testing can -determine.. - -* The Borland version of the dll fails some of the tests with a memory read -exception. The cause is not yet known but a compiler bug has not been ruled -out. - - -RELEASE 2.3.0 -------------- -(2005-04-12) - -General -------- - -Release 1.7.0 is a backport of features and bug fixes new in -this release. See earlier notes under Release 2.0.0/General. - -Bugs fixed ----------- - -* Fixed pthread_once potential for post once_routine cancellation -hanging due to starvation. See comments in pthread_once.c. -Momentary priority boosting is used to ensure that, after a -once_routine is cancelled, the thread that will run the -once_routine is not starved by higher priority waiting threads at -critical times. Priority boosting occurs only AFTER a once_routine -cancellation, and is applied only to that once_control. The -once_routine is run at the thread's normal base priority. - -New tests ---------- - -* once4.c: Aggressively tests pthread_once() under realtime -conditions using threads with varying priorities. Windows' -random priority boosting does not occur for threads with realtime -priority levels. - - -RELEASE 2.2.0 -------------- -(2005-04-04) - -General -------- - -* Added makefile targets to build static link versions of the library. -Both MinGW and MSVC. Please note that this does not imply any change -to the LGPL licensing, which still imposes psecific conditions on -distributing software that has been statically linked with this library. - -* There is a known bug in pthread_once(). Cancellation of the init_routine -exposes a potential starvation (i.e. deadlock) problem if a waiting thread -has a higher priority than the initting thread. This problem will be fixed -in version 3.0.0 of the library. - -Bugs fixed ----------- - -* Fix integer overrun error in sem_timedwait(). -Kevin Lussier - -* Fix preprocessor directives for static linking. -Dimitar Panayotov - - -RELEASE 2.1.0 -------------- -(2005-03-16) - -Bugs fixed ----------- - -* Reverse change to pthread_setcancelstate() in 2.0.0. - - -RELEASE 2.0.0 -------------- -(2005-03-16) - -General -------- - -This release represents an ABI change and the DLL version naming has -incremented from 1 to 2, e.g. pthreadVC2.dll. - -Version 1.4.0 back-ports the new functionality included in this -release. Please distribute DLLs built from that version with updates -to applications built on pthreads-win32 version 1.x.x. - -The package naming has changed, replacing the snapshot date with -the version number + descriptive information. E.g. this -release is "pthreads-w32-2-0-0-release". - -Bugs fixed ----------- - -* pthread_setcancelstate() no longer checks for a pending -async cancel event if the library is using alertable async -cancel. See the README file (Prerequisites section) for info -on adding alertable async cancelation. - -New features ------------- - -* pthread_once() now supports init_routine cancellability. - -New tests ---------- - -* Agressively test pthread_once() init_routine cancellability. - - -SNAPSHOT 2005-03-08 -------------------- -Version 1.3.0 - -Bug reports (fixed) -------------------- - -* Implicitly created threads leave Win32 handles behind after exiting. -- Dmitrii Semii - -* pthread_once() starvation problem. -- Gottlob Frege - -New tests ---------- - -* More intense testing of pthread_once(). - - -SNAPSHOT 2005-01-25 -------------------- -Version 1.2.0 - -Bug fixes ---------- - -* Attempted acquisition of a recursive mutex could cause waiting threads -to not be woken when the mutex was released. -- Ralf Kubis - -* Various package omissions have been fixed. - - -SNAPSHOT 2005-01-03 -------------------- -Version 1.1.0 - -Bug fixes ---------- - -* Unlocking recursive or errorcheck mutexes would sometimes -unexpectedly return an EPERM error (bug introduced in -snapshot-2004-11-03). -- Konstantin Voronkov - - -SNAPSHOT 2004-11-22 -------------------- -Version 1.0.0 - -This snapshot primarily fixes the condvar bug introduced in -snapshot-2004-11-03. DLL versioning has also been included to allow -applications to runtime check the Microsoft compatible DLL version -information, and to extend the DLL naming system for ABI and major -(non-backward compatible) API changes. See the README file for details. - -Bug fixes ---------- - -* Condition variables no longer deadlock (bug introduced in -snapshot-2004-11-03). -- Alexander Kotliarov and Nicolas at saintmac - -* DLL naming extended to avoid 'DLL hell' in the future, and to -accommodate the ABI change introduced in snapshot-2004-11-03. Snapshot -2004-11-03 will be removed from FTP sites. - -New features ------------- - -* A Microsoft-style version resource has been added to the DLL for -applications that wish to check DLL compatibility at runtime. - -* Pthreads-win32 DLL naming has been extended to allow incompatible DLL -versions to co-exist in the same filesystem. See the README file for details, -but briefly: while the version information inside the DLL will change with -each release from now on, the DLL version names will only change if the new -DLL is not backward compatible with older applications. - -The versioning scheme has been borrowed from GNU Libtool, and the DLL -naming scheme is from Cygwin. Provided the Libtool-style numbering rules are -honoured, the Cygwin DLL naming scheme automatcally ensures that DLL name -changes are minimal and that applications will not load an incompatible -pthreads-win32 DLL. - -Those who use the pre-built DLLs will find that the DLL/LIB names have a new -suffix (1) in this snapshot. E.g. pthreadVC1.dll etc. - -* The POSIX thread ID reuse uniqueness feature introduced in the last snapshot -has been kept as default, but the behaviour can now be controlled when the DLL -is built to effectively switch it off. This makes the library much more -sensitive to applications that assume that POSIX thread IDs are unique, i.e. -are not strictly compliant with POSIX. See the PTW32_THREAD_ID_REUSE_INCREMENT -macro comments in config.h for details. - -Other changes -------------- -Certain POSIX macros have changed. - -These changes are intended to conform to the Single Unix Specification version 3, -which states that, if set to 0 (zero) or not defined, then applications may use -sysconf() to determine their values at runtime. Pthreads-win32 does not -implement sysconf(). - -The following macros are no longer undefined, but defined and set to -1 -(not implemented): - - _POSIX_THREAD_ATTR_STACKADDR - _POSIX_THREAD_PRIO_INHERIT - _POSIX_THREAD_PRIO_PROTECT - _POSIX_THREAD_PROCESS_SHARED - -The following macros are defined and set to 200112L (implemented): - - _POSIX_THREADS - _POSIX_THREAD_SAFE_FUNCTIONS - _POSIX_THREAD_ATTR_STACKSIZE - _POSIX_THREAD_PRIORITY_SCHEDULING - _POSIX_SEMAPHORES - _POSIX_READER_WRITER_LOCKS - _POSIX_SPIN_LOCKS - _POSIX_BARRIERS - -The following macros are defined and set to appropriate values: - - _POSIX_THREAD_THREADS_MAX - _POSIX_SEM_VALUE_MAX - _POSIX_SEM_NSEMS_MAX - PTHREAD_DESTRUCTOR_ITERATIONS - PTHREAD_KEYS_MAX - PTHREAD_STACK_MIN - PTHREAD_THREADS_MAX - - -SNAPSHOT 2004-11-03 -------------------- - -DLLs produced from this snapshot cannot be used with older applications without -recompiling the application, due to a change to pthread_t to provide unique POSIX -thread IDs. - -Although this snapshot passes the extended test suite, many of the changes are -fairly major, and some applications may show different behaviour than previously, -so adopt with care. Hopefully, any changed behaviour will be due to the library -being better at it's job, not worse. - -Bug fixes ---------- - -* pthread_create() no longer accepts NULL as the thread reference arg. -A segfault (memory access fault) will result, and no thread will be -created. - -* pthread_barrier_wait() no longer acts as a cancelation point. - -* Fix potential race condition in pthread_once() -- Tristan Savatier - -* Changes to pthread_cond_destroy() exposed some coding weaknesses in several -test suite mini-apps because pthread_cond_destroy() now returns EBUSY if the CV -is still in use. - -New features ------------- - -* Added for compatibility: -PTHREAD_RECURSIVE_MUTEX_INITIALIZER, -PTHREAD_ERRORCHECK_MUTEX_INITIALIZER, -PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, -PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP - -* Initial support for Digital Mars compiler -- Anuj Goyal - -* Faster Mutexes. These have been been rewritten following a model provided by -Alexander Terekhov that reduces kernel space checks, and eliminates some additional -critical sections used to manage a race between timedlock expiration and unlock. -Please be aware that the new mutexes do not enforce strict absolute FIFO scheduling -of mutexes, however any out-of-order lock acquisition should be very rare. - -* Faster semaphores. Following a similar model to mutexes above, these have been -rewritten to use preliminary users space checks. - -* sem_getvalue() now returns the number of waiters. - -* The POSIX thread ID now has much stronger uniqueness characteristics. The library -garrantees not to reuse the same thread ID for at least 2^(wordsize) thread -destruction/creation cycles. - -New tests ---------- - -* semaphore4.c: Tests cancelation of the new sem_wait(). - -* semaphore4t.c: Likewise for sem_timedwait(). - -* rwlock8.c: Tests and times the slow execution paths of r/w locks, and the CVs, -mutexes, and semaphores that they're built on. - - -SNAPSHOT 2004-05-16 -------------------- - -Attempt to add Watcom to the list of compilers that can build the library. -This failed in the end due to it's non-thread-aware errno. The library -builds but the test suite fails. See README.Watcom for more details. - -Bug fixes ---------- -* Bug and memory leak in sem_init() -- Alex Blanco - -* ptw32_getprocessors() now returns CPU count of 1 for WinCE. -- James Ewing - -* pthread_cond_wait() could be canceled at a point where it should not -be cancelable. Fixed. -- Alexander Terekhov - -* sem_timedwait() had an incorrect timeout calculation. -- Philippe Di Cristo - -* Fix a memory leak left behind after threads are destroyed. -- P. van Bruggen - -New features ------------- -* Ported to AMD64. -- Makoto Kato - -* True pre-emptive asynchronous cancelation of threads. This is optional -and requires that Panagiotis E. Hadjidoukas's QueueUserAPCEx package be -installed. This package is included in the pthreads-win32 self-unpacking -Zip archive starting from this snapshot. See the README.txt file inside -the package for installation details. - -Note: If you don't use async cancelation in your application, or don't need -to cancel threads that are blocked on system resources such as network I/O, -then the default non-preemptive async cancelation is probably good enough. -However, pthreads-win32 auto-detects the availability of these components -at run-time, so you don't need to rebuild the library from source if you -change your mind later. - -All of the advice available in books and elsewhere on the undesirability -of using async cancelation in any application still stands, but this -feature is a welcome addition with respect to the library's conformance to -the POSIX standard. - -SNAPSHOT 2003-09-18 -------------------- - -Cleanup of thread priority management. In particular, setting of thread -priority now attempts to map invalid Win32 values within the range returned -by sched_get_priority_min/max() to useful values. See README.NONPORTABLE -under "Thread priority". - -Bug fixes ---------- -* pthread_getschedparam() now returns the priority given by the most recent -call to pthread_setschedparam() or established by pthread_create(), as -required by the standard. Previously, pthread_getschedparam() incorrectly -returned the running thread priority at the time of the call, which may have -been adjusted or temporarily promoted/demoted. - -* sched_get_priority_min() and sched_get_priority_max() now return -1 on error -and set errno. Previously, they incorrectly returned the error value directly. - - -SNAPSHOT 2003-09-04 -------------------- - -Bug fixes ---------- -* ptw32_cancelableWait() now allows cancelation of waiting implicit POSIX -threads. - -New test --------- -* cancel8.c tests cancelation of Win32 threads waiting at a POSIX cancelation -point. - - -SNAPSHOT 2003-09-03 -------------------- - -Bug fixes ---------- -* pthread_self() would free the newly created implicit POSIX thread handle if -DuplicateHandle failed instead of recycle it (very unlikely). - -* pthread_exit() was neither freeing nor recycling the POSIX thread struct -for implicit POSIX threads. - -New feature - Cancelation of/by Win32 (non-POSIX) threads ---------------------------------------------------------- -Since John Bossom's original implementation, the library has allowed non-POSIX -initialised threads (Win32 threads) to call pthreads-win32 routines and -therefore interact with POSIX threads. This is done by creating an on-the-fly -POSIX thread ID for the Win32 thread that, once created, allows fully -reciprical interaction. This did not extend to thread cancelation (async or -deferred). Now it does. - -Any thread can be canceled by any other thread (Win32 or POSIX) if the former -thread's POSIX pthread_t value is known. It's TSD destructors and POSIX -cleanup handlers will be run before the thread exits with an exit code of -PTHREAD_CANCELED (retrieved with GetExitCodeThread()). - -This allows a Win32 thread to, for example, call POSIX CV routines in the same way -that POSIX threads would/should, with pthread_cond_wait() cancelability and -cleanup handlers (pthread_cond_wait() is a POSIX cancelation point). - -By adding cancelation, Win32 threads should now be able to call all POSIX -threads routines that make sense including semaphores, mutexes, condition -variables, read/write locks, barriers, spinlocks, tsd, cleanup push/pop, -cancelation, pthread_exit, scheduling, etc. - -Note that these on-the-fly 'implicit' POSIX thread IDs are initialised as detached -(not joinable) with deferred cancelation type. The POSIX thread ID will be created -automatically by any POSIX routines that need a POSIX handle (unless the routine -needs a pthread_t as a parameter of course). A Win32 thread can discover it's own -POSIX thread ID by calling pthread_self(), which will create the handle if -necessary and return the pthread_t value. - -New tests ---------- -Test the above new feature. - - -SNAPSHOT 2003-08-19 -------------------- - -This snapshot fixes some accidental corruption to new test case sources. -There are no changes to the library source code. - - -SNAPSHOT 2003-08-15 -------------------- - -Bug fixes ---------- - -* pthread.dsp now uses correct compile flags (/MD). -- Viv - -* pthread_win32_process_detach_np() fixed memory leak. -- Steven Reddie - -* pthread_mutex_destroy() fixed incorrect return code. -- Nicolas Barry - -* pthread_spin_destroy() fixed memory leak. -- Piet van Bruggen - -* Various changes to tighten arg checking, and to work with later versions of -MinGW32 and MsysDTK. - -* pthread_getschedparam() etc, fixed dangerous thread validity checking. -- Nicolas Barry - -* POSIX thread handles are now reused and their memory is not freed on thread exit. -This allows for stronger thread validity checking. - -New standard routine --------------------- - -* pthread_kill() added to provide thread validity checking to applications. -It does not accept any non zero values for the signal arg. - -New test cases --------------- - -* New test cases to confirm validity checking, pthread_kill(), and thread reuse. - - -SNAPSHOT 2003-05-10 -------------------- - -Bug fixes ---------- - -* pthread_mutex_trylock() now returns correct error values. -pthread_mutex_destroy() will no longer destroy a recursively locked mutex. -pthread_mutex_lock() is no longer inadvertantly behaving as a cancelation point. -- Thomas Pfaff - -* pthread_mutex_timedlock() no longer occasionally sets incorrect mutex -ownership, causing deadlocks in some applications. -- Robert Strycek and Alexander Terekhov - - -SNAPSHOT 2002-11-04 -------------------- - -Bug fixes ---------- - -* sem_getvalue() now returns the correct value under Win NT and WinCE. -- Rob Fanner - -* sem_timedwait() now uses tighter checks for unreasonable -abstime values - that would result in unexpected timeout values. - -* ptw32_cond_wait_cleanup() no longer mysteriously consumes -CV signals but may produce more spurious wakeups. It is believed -that the sem_timedwait() call is consuming a CV signal that it -shouldn't. -- Alexander Terekhov - -* Fixed a memory leak in ptw32_threadDestroy() for implicit threads. - -* Fixed potential for deadlock in pthread_cond_destroy(). -A deadlock could occur for statically declared CVs (PTHREAD_COND_INITIALIZER), -when one thread is attempting to destroy the condition variable while another -is attempting to dynamically initialize it. -- Michael Johnson - - -SNAPSHOT 2002-03-02 -------------------- - -Cleanup code default style. (IMPORTANT) ----------------------------------------------------------------------- -Previously, if not defined, the cleanup style was determined automatically -from the compiler/language, and one of the following was defined accordingly: - - __CLEANUP_SEH MSVC only - __CLEANUP_CXX C++, including MSVC++, GNU G++ - __CLEANUP_C C, including GNU GCC, not MSVC - -These defines determine the style of cleanup (see pthread.h) and, -most importantly, the way that cancelation and thread exit (via -pthread_exit) is performed (see the routine ptw32_throw() in private.c). - -In short, the exceptions versions of the library throw an exception -when a thread is canceled or exits (via pthread_exit()), which is -caught by a handler in the thread startup routine, so that the -the correct stack unwinding occurs regardless of where the thread -is when it's canceled or exits via pthread_exit(). - -In this and future snapshots, unless the build explicitly defines (e.g. -via a compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then -the build NOW always defaults to __CLEANUP_C style cleanup. This style -uses setjmp/longjmp in the cancelation and pthread_exit implementations, -and therefore won't do stack unwinding even when linked to applications -that have it (e.g. C++ apps). This is for consistency with most -current commercial Unix POSIX threads implementations. Compaq's TRU64 -may be an exception (no pun intended) and possible future trend. - -Although it was not clearly documented before, it is still necessary to -build your application using the same __CLEANUP_* define as was -used for the version of the library that you link with, so that the -correct parts of pthread.h are included. That is, the possible -defines require the following library versions: - - __CLEANUP_SEH pthreadVSE.dll - __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll - __CLEANUP_C pthreadVC.dll or pthreadGC.dll - -E.g. regardless of whether your app is C or C++, if you link with -pthreadVC.lib or libpthreadGC.a, then you must define __CLEANUP_C. - - -THE POINT OF ALL THIS IS: if you have not been defining one of these -explicitly, then the defaults as described at the top of this -section were being used. - -THIS NOW CHANGES, as has been explained above, but to try to make this -clearer here's an example: - -If you were building your application with MSVC++ i.e. using C++ -exceptions and not explicitly defining one of __CLEANUP_*, then -__CLEANUP_C++ was automatically defined for you in pthread.h. -You should have been linking with pthreadVCE.dll, which does -stack unwinding. - -If you now build your application as you had before, pthread.h will now -automatically set __CLEANUP_C as the default style, and you will need to -link with pthreadVC.dll. Stack unwinding will now NOT occur when a thread -is canceled, or the thread calls pthread_exit(). - -Your application will now most likely behave differently to previous -versions, and in non-obvious ways. Most likely is that locally -instantiated objects may not be destroyed or cleaned up after a thread -is canceled. - -If you want the same behaviour as before, then you must now define -__CLEANUP_C++ explicitly using a compiler option and link with -pthreadVCE.dll as you did before. - - -WHY ARE WE MAKING THE DEFAULT STYLE LESS EXCEPTION-FRIENDLY? -Because no commercial Unix POSIX threads implementation allows you to -choose to have stack unwinding. Therefore, providing it in pthread-win32 -as a default is dangerous. We still provide the choice but unless -you consciously choose to do otherwise, your pthreads applications will -now run or crash in similar ways irrespective of the threads platform -you use. Or at least this is the hope. - - -WHY NOT REMOVE THE EXCEPTIONS VERSIONS OF THE LIBRARY ALTOGETHER? -There are a few reasons: -- because there are well respected POSIX threads people who believe - that POSIX threads implementations should be exceptions aware and - do the expected thing in that context. (There are equally respected - people who believe it should not be easily accessible, if it's there - at all, for unconditional conformity to other implementations.) -- because pthreads-win32 is one of the few implementations that has - the choice, perhaps the only freely available one, and so offers - a laboratory to people who may want to explore the effects; -- although the code will always be around somewhere for anyone who - wants it, once it's removed from the current version it will not be - nearly as visible to people who may have a use for it. - - -Source module splitting ------------------------ -In order to enable smaller image sizes to be generated -for applications that link statically with the library, -most routines have been separated out into individual -source code files. - -This is being done in such a way as to be backward compatible. -The old source files are reused to congregate the individual -routine files into larger translation units (via a bunch of -# includes) so that the compiler can still optimise wherever -possible, e.g. through inlining, which can only be done -within the same translation unit. - -It is also possible to build the entire library by compiling -the single file named "pthread.c", which just #includes all -the secondary congregation source files. The compiler -may be able to use this to do more inlining of routines. - -Although the GNU compiler is able to produce libraries with -the necessary separation (the -ffunction-segments switch), -AFAIK, the MSVC and other compilers don't have this feature. - -Finally, since I use makefiles and command-line compilation, -I don't know what havoc this reorganisation may wreak amongst -IDE project file users. You should be able to continue -using your existing project files without modification. - - -New non-portable functions --------------------------- -pthread_num_processors_np(): - Returns the number of processors in the system that are - available to the process, as determined from the processor - affinity mask. - -pthread_timechange_handler_np(): - To improve tolerance against operator or time service initiated - system clock changes. - - This routine can be called by an application when it - receives a WM_TIMECHANGE message from the system. At present - it broadcasts all condition variables so that waiting threads - can wake up and re-evaluate their conditions and restart - their timed waits if required. - - Suggested by Alexander Terekhov - - -Platform dependence -------------------- -As Win95 doesn't provide one, the library now contains -it's own InterlockedCompareExchange() routine, which is used -whenever Windows doesn't provide it. InterlockedCompareExchange() -is used to implement spinlocks and barriers, and also in mutexes. -This routine relies on the CMPXCHG machine instruction which -is not available on i386 CPUs. This library (from snapshot -20010712 onwards) is therefore no longer supported on i386 -processor platforms. - - -New standard routines ---------------------- -For source code portability only - rwlocks cannot be process shared yet. - - pthread_rwlockattr_init() - pthread_rwlockattr_destroy() - pthread_rwlockattr_setpshared() - pthread_rwlockattr_getpshared() - -As defined in the new POSIX standard, and the Single Unix Spec version 3: - - sem_timedwait() - pthread_mutex_timedlock() - Alexander Terekhov and Thomas Pfaff - pthread_rwlock_timedrdlock() - adapted from pthread_rwlock_rdlock() - pthread_rwlock_timedwrlock() - adapted from pthread_rwlock_wrlock() - - -pthread.h no longer includes windows.h --------------------------------------- -[Not yet for G++] - -This was done to prevent conflicts. - -HANDLE, DWORD, and NULL are temporarily defined within pthread.h if -they are not already. - - -pthread.h, sched.h and semaphore.h now use dllexport/dllimport --------------------------------------------------------------- -Not only to avoid the need for the pthread.def file, but to -improve performance. Apparently, declaring functions with dllimport -generates a direct call to the function and avoids the overhead -of a stub function call. - -Bug fixes ---------- -* Fixed potential NULL pointer dereferences in pthread_mutexattr_init, -pthread_mutexattr_getpshared, pthread_barrierattr_init, -pthread_barrierattr_getpshared, and pthread_condattr_getpshared. -- Scott McCaskill - -* Removed potential race condition in pthread_mutex_trylock and -pthread_mutex_lock; -- Alexander Terekhov - -* The behaviour of pthread_mutex_trylock in relation to -recursive mutexes was inconsistent with commercial implementations. -Trylock would return EBUSY if the lock was owned already by the -calling thread regardless of mutex type. Trylock now increments the -recursion count and returns 0 for RECURSIVE mutexes, and will -return EDEADLK rather than EBUSY for ERRORCHECK mutexes. This is -consistent with Solaris. -- Thomas Pfaff - -* Found a fix for the library and workaround for applications for -the known bug #2, i.e. where __CLEANUP_CXX or __CLEANUP_SEH is defined. -See the "Known Bugs in this snapshot" section below. - -This could be made transparent to applications by replacing the macros that -define the current C++ and SEH versions of pthread_cleanup_push/pop -with the C version, but AFAIK cleanup handlers would not then run in the -correct sequence with destructors and exception cleanup handlers when -an exception occurs. - -* Cancelation once started in a thread cannot now be inadvertantly -double canceled. That is, once a thread begins it's cancelation run, -cancelation is disabled and a subsequent cancel request will -return an error (ESRCH). - -* errno: An incorrect compiler directive caused a local version -of errno to be used instead of the Win32 errno. Both instances are -thread-safe but applications checking errno after a pthreads-win32 -call would be wrong. Fixing this also fixed a bad compiler -option in the testsuite (/MT should have been /MD) which is -needed to link with the correct library MSVCRT.LIB. - - -SNAPSHOT 2001-07-12 -------------------- - -To be added - - -SNAPSHOT 2001-07-03 -------------------- - -To be added - - -SNAPSHOT 2000-08-13 -------------------- - -New: -- Renamed DLL and LIB files: - pthreadVSE.dll (MS VC++/Structured EH) - pthreadVSE.lib - pthreadVCE.dll (MS VC++/C++ EH) - pthreadVCE.lib - pthreadGCE.dll (GNU G++/C++ EH) - libpthreadw32.a - - Both your application and the pthread dll should use the - same exception handling scheme. - -Bugs fixed: -- MSVC++ C++ exception handling. - -Some new tests have been added. - - -SNAPSHOT 2000-08-10 -------------------- - -New: -- asynchronous cancelation on X86 (Jason Nye) -- Makefile compatible with MS nmake to replace - buildlib.bat -- GNUmakefile for Mingw32 -- tests/Makefile for MS nmake replaces runall.bat -- tests/GNUmakefile for Mingw32 - -Bugs fixed: -- kernel32 load/free problem -- attempt to hide internel exceptions from application - exception handlers (__try/__except and try/catch blocks) -- Win32 thread handle leakage bug - (David Baggett/Paul Redondo/Eyal Lebedinsky) - -Some new tests have been added. - - -SNAPSHOT 1999-11-02 -------------------- - -Bugs fixed: -- ctime_r macro had an incorrect argument (Erik Hensema), -- threads were not being created - PTHREAD_CANCEL_DEFERRED. This should have - had little effect as deferred is the only - supported type. (Ross Johnson). - -Some compatibility improvements added, eg. -- pthread_setcancelstate accepts NULL pointer - for the previous value argument. Ditto for - pthread_setcanceltype. This is compatible - with Solaris but should not affect - standard applications (Erik Hensema) - -Some new tests have been added. - - -SNAPSHOT 1999-10-17 -------------------- - -Bug fix - Cancelation of threads waiting on condition variables -now works properly (Lorin Hochstein and Peter Slacik) - - -SNAPSHOT 1999-08-12 -------------------- - -Fixed exception stack cleanup if calling pthread_exit() -- (Lorin Hochstein and John Bossom). - -Fixed bugs in condition variables - (Peter Slacik): - - additional contention checks - - properly adjust number of waiting threads after timed - condvar timeout. - - -SNAPSHOT 1999-05-30 -------------------- - -Some minor bugs have been fixed. See the ChangeLog file for details. - -Some more POSIX 1b functions are now included but ony return an -error (ENOSYS) if called. They are: - - sem_open - sem_close - sem_unlink - sem_getvalue - - -SNAPSHOT 1999-04-07 -------------------- - -Some POSIX 1b functions which were internally supported are now -available as exported functions: - - sem_init - sem_destroy - sem_wait - sem_trywait - sem_post - sched_yield - sched_get_priority_min - sched_get_priority_max - -Some minor bugs have been fixed. See the ChangeLog file for details. - - -SNAPSHOT 1999-03-16 -------------------- - -Initial release. - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/PROGRESS b/bridge/third_party/quickjs/compat/win32/pthreads/PROGRESS deleted file mode 100644 index 9abf0bca47..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/PROGRESS +++ /dev/null @@ -1,4 +0,0 @@ -Please see the ANNOUNCE file "Level of Standards Conformance" -or the web page: - -http://sources.redhat.com/pthreads-win32/conformance.html diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README b/bridge/third_party/quickjs/compat/win32/pthreads/README deleted file mode 100644 index 545360bfa7..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README +++ /dev/null @@ -1,601 +0,0 @@ -PTHREADS-WIN32 -============== - -Pthreads-win32 is free software, distributed under the GNU Lesser -General Public License (LGPL). See the file 'COPYING.LIB' for terms -and conditions. Also see the file 'COPYING' for information -specific to pthreads-win32, copyrights and the LGPL. - - -What is it? ------------ - -Pthreads-win32 is an Open Source Software implementation of the -Threads component of the POSIX 1003.1c 1995 Standard (or later) -for Microsoft's Win32 environment. Some functions from POSIX -1003.1b are also supported including semaphores. Other related -functions include the set of read-write lock functions. The -library also supports some of the functionality of the Open -Group's Single Unix specification, version 2, namely mutex types, -plus some common and pthreads-win32 specific non-portable -routines (see README.NONPORTABLE). - -See the file "ANNOUNCE" for more information including standards -conformance details and the list of supported and unsupported -routines. - - -Prerequisites -------------- -MSVC or GNU C (MinGW32 MSys development kit) - To build from source. - -QueueUserAPCEx by Panagiotis E. Hadjidoukas - To support any thread cancelation in C++ library builds or - to support cancelation of blocked threads in any build. - This library is not required otherwise. - - For true async cancelation of threads (including blocked threads). - This is a DLL and Windows driver that provides pre-emptive APC - by forcing threads into an alertable state when the APC is queued. - Both the DLL and driver are provided with the pthreads-win32.exe - self-unpacking ZIP, and on the pthreads-win32 FTP site (in source - and pre-built forms). Currently this is a separate LGPL package to - pthreads-win32. See the README in the QueueUserAPCEx folder for - installation instructions. - - Pthreads-win32 will automatically detect if the QueueUserAPCEx DLL - QuserEx.DLL is available and whether the driver AlertDrv.sys is - loaded. If it is not available, pthreads-win32 will simulate async - cancelation, which means that it can async cancel only threads that - are runnable. The simulated async cancellation cannot cancel blocked - threads. - - [FOR SECURITY] To be found Quserex.dll MUST be installed in the - Windows System Folder. This is not an unreasonable constraint given a - driver must also be installed and loaded at system startup. - - -Library naming --------------- - -Because the library is being built using various exception -handling schemes and compilers - and because the library -may not work reliably if these are mixed in an application, -each different version of the library has it's own name. - -Note 1: the incompatibility is really between EH implementations -of the different compilers. It should be possible to use the -standard C version from either compiler with C++ applications -built with a different compiler. If you use an EH version of -the library, then you must use the same compiler for the -application. This is another complication and dependency that -can be avoided by using only the standard C library version. - -Note 2: if you use a standard C pthread*.dll with a C++ -application, then any functions that you define that are -intended to be called via pthread_cleanup_push() must be -__cdecl. - -Note 3: the intention was to also name either the VC or GC -version (it should be arbitrary) as pthread.dll, including -pthread.lib and libpthread.a as appropriate. This is no longer -likely to happen. - -Note 4: the compatibility number was added so that applications -can differentiate between binary incompatible versions of the -libs and dlls. - -In general: - pthread[VG]{SE,CE,C}[c].dll - pthread[VG]{SE,CE,C}[c].lib - -where: - [VG] indicates the compiler - V - MS VC, or - G - GNU C - - {SE,CE,C} indicates the exception handling scheme - SE - Structured EH, or - CE - C++ EH, or - C - no exceptions - uses setjmp/longjmp - - c - DLL compatibility number indicating ABI and API - compatibility with applications built against - a snapshot with the same compatibility number. - See 'Version numbering' below. - -The name may also be suffixed by a 'd' to indicate a debugging version -of the library. E.g. pthreadVC2d.lib. Debugging versions contain -additional information for debugging (symbols etc) and are often not -optimised in any way (compiled with optimisation turned off). - -Examples: - pthreadVSE.dll (MSVC/SEH) - pthreadGCE.dll (GNUC/C++ EH) - pthreadGC.dll (GNUC/not dependent on exceptions) - pthreadVC1.dll (MSVC/not dependent on exceptions - not binary - compatible with pthreadVC.dll) - pthreadVC2.dll (MSVC/not dependent on exceptions - not binary - compatible with pthreadVC1.dll or pthreadVC.dll) - -The GNU library archive file names have correspondingly changed to: - - libpthreadGCEc.a - libpthreadGCc.a - - -Versioning numbering --------------------- - -Version numbering is separate from the snapshot dating system, and -is the canonical version identification system embedded within the -DLL using the Microsoft version resource system. The versioning -system chosen follows the GNU Libtool system. See -http://www.gnu.org/software/libtool/manual.html section 6.2. - -See the resource file 'version.rc'. - -Microsoft version numbers use 4 integers: - - 0.0.0.0 - -Pthreads-win32 uses the first 3 following the Libtool convention. -The fourth is commonly used for the build number, but will be reserved -for future use. - - current.revision.age.0 - -The numbers are changed as follows: - -1. If the library source code has changed at all since the last update, - then increment revision (`c:r:a' becomes `c:r+1:a'). -2. If any interfaces have been added, removed, or changed since the last - update, increment current, and set revision to 0. -3. If any interfaces have been added since the last public release, then - increment age. -4. If any interfaces have been removed or changed since the last public - release, then set age to 0. - - -DLL compatibility numbering is an attempt to ensure that applications -always load a compatible pthreads-win32 DLL by using a DLL naming system -that is consistent with the version numbering system. It also allows -older and newer DLLs to coexist in the same filesystem so that older -applications can continue to be used. For pre .NET Windows systems, -this inevitably requires incompatible versions of the same DLLs to have -different names. - -Pthreads-win32 has adopted the Cygwin convention of appending a single -integer number to the DLL name. The number used is based on the library -version number and is computed as 'current' - 'age'. - -(See http://home.att.net/~perlspinr/libversioning.html for a nicely -detailed explanation.) - -Using this method, DLL name/s will only change when the DLL's -backwards compatibility changes. Note that the addition of new -'interfaces' will not of itself change the DLL's compatibility for older -applications. - - -Which of the several dll versions to use? ------------------------------------------ -or, ---- -What are all these pthread*.dll and pthread*.lib files? -------------------------------------------------------- - -Simple, use either pthreadGCv.* if you use GCC, or pthreadVCv.* if you -use MSVC - where 'v' is the DLL versioning (compatibility) number. - -Otherwise, you need to choose carefully and know WHY. - -The most important choice you need to make is whether to use a -version that uses exceptions internally, or not. There are versions -of the library that use exceptions as part of the thread -cancelation and exit implementation. The default version uses -setjmp/longjmp. - -There is some contension amongst POSIX threads experts as -to how POSIX threads cancelation and exit should work -with languages that use exceptions, e.g. C++ and even C -(Microsoft's Structured Exceptions). - -The issue is: should cancelation of a thread in, say, -a C++ application cause object destructors and C++ exception -handlers to be invoked as the stack unwinds during thread -exit, or not? - -There seems to be more opinion in favour of using the -standard C version of the library (no EH) with C++ applications -for the reason that this appears to be the assumption commercial -pthreads implementations make. Therefore, if you use an EH version -of pthreads-win32 then you may be under the illusion that -your application will be portable, when in fact it is likely to -behave differently when linked with other pthreads libraries. - -Now you may be asking: then why have you kept the EH versions of -the library? - -There are a couple of reasons: -- there is division amongst the experts and so the code may - be needed in the future. Yes, it's in the repository and we - can get it out anytime in the future, but it would be difficult - to find. -- pthreads-win32 is one of the few implementations, and possibly - the only freely available one, that has EH versions. It may be - useful to people who want to play with or study application - behaviour under these conditions. - -Notes: - -[If you use either pthreadVCE or pthreadGCE] - -1. [See also the discussion in the FAQ file - Q2, Q4, and Q5] - -If your application contains catch(...) blocks in your POSIX -threads then you will need to replace the "catch(...)" with the macro -"PtW32Catch", eg. - - #ifdef PtW32Catch - PtW32Catch { - ... - } - #else - catch(...) { - ... - } - #endif - -Otherwise neither pthreads cancelation nor pthread_exit() will work -reliably when using versions of the library that use C++ exceptions -for cancelation and thread exit. - -This is due to what is believed to be a C++ compliance error in VC++ -whereby you may not have multiple handlers for the same exception in -the same try/catch block. GNU G++ doesn't have this restriction. - - -Other name changes ------------------- - -All snapshots prior to and including snapshot 2000-08-13 -used "_pthread_" as the prefix to library internal -functions, and "_PTHREAD_" to many library internal -macros. These have now been changed to "ptw32_" and "PTW32_" -respectively so as to not conflict with the ANSI standard's -reservation of identifiers beginning with "_" and "__" for -use by compiler implementations only. - -If you have written any applications and you are linking -statically with the pthreads-win32 library then you may have -included a call to _pthread_processInitialize. You will -now have to change that to ptw32_processInitialize. - - -Cleanup code default style --------------------------- - -Previously, if not defined, the cleanup style was determined automatically -from the compiler used, and one of the following was defined accordingly: - - __CLEANUP_SEH MSVC only - __CLEANUP_CXX C++, including MSVC++, GNU G++ - __CLEANUP_C C, including GNU GCC, not MSVC - -These defines determine the style of cleanup (see pthread.h) and, -most importantly, the way that cancelation and thread exit (via -pthread_exit) is performed (see the routine ptw32_throw()). - -In short, the exceptions versions of the library throw an exception -when a thread is canceled, or exits via pthread_exit(). This exception is -caught by a handler in the thread startup routine, so that the -the correct stack unwinding occurs regardless of where the thread -is when it's canceled or exits via pthread_exit(). - -In this snapshot, unless the build explicitly defines (e.g. via a -compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then -the build NOW always defaults to __CLEANUP_C style cleanup. This style -uses setjmp/longjmp in the cancelation and pthread_exit implementations, -and therefore won't do stack unwinding even when linked to applications -that have it (e.g. C++ apps). This is for consistency with most/all -commercial Unix POSIX threads implementations. - -Although it was not clearly documented before, it is still necessary to -build your application using the same __CLEANUP_* define as was -used for the version of the library that you link with, so that the -correct parts of pthread.h are included. That is, the possible -defines require the following library versions: - - __CLEANUP_SEH pthreadVSE.dll - __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll - __CLEANUP_C pthreadVC.dll or pthreadGC.dll - -It is recommended that you let pthread.h use it's default __CLEANUP_C -for both library and application builds. That is, don't define any of -the above, and then link with pthreadVC.lib (MSVC or MSVC++) and -libpthreadGC.a (MinGW GCC or G++). The reason is explained below, but -another reason is that the prebuilt pthreadVCE.dll is currently broken. -Versions built with MSVC++ later than version 6 may not be broken, but I -can't verify this yet. - -WHY ARE WE MAKING THE DEFAULT STYLE LESS EXCEPTION-FRIENDLY? -Because no commercial Unix POSIX threads implementation allows you to -choose to have stack unwinding. Therefore, providing it in pthread-win32 -as a default is dangerous. We still provide the choice but unless -you consciously choose to do otherwise, your pthreads applications will -now run or crash in similar ways irrespective of the pthreads platform -you use. Or at least this is the hope. - - -Building under VC++ using C++ EH, Structured EH, or just C ----------------------------------------------------------- - -From the source directory run nmake without any arguments to list -help information. E.g. - -$ nmake - -Microsoft (R) Program Maintenance Utility Version 6.00.8168.0 -Copyright (C) Microsoft Corp 1988-1998. All rights reserved. - -Run one of the following command lines: -nmake clean VCE (to build the MSVC dll with C++ exception handling) -nmake clean VSE (to build the MSVC dll with structured exception handling) -nmake clean VC (to build the MSVC dll with C cleanup code) -nmake clean VCE-inlined (to build the MSVC inlined dll with C++ exception handling) -nmake clean VSE-inlined (to build the MSVC inlined dll with structured exception handling) -nmake clean VC-inlined (to build the MSVC inlined dll with C cleanup code) -nmake clean VC-static (to build the MSVC static lib with C cleanup code) -nmake clean VCE-debug (to build the debug MSVC dll with C++ exception handling) -nmake clean VSE-debug (to build the debug MSVC dll with structured exception handling) -nmake clean VC-debug (to build the debug MSVC dll with C cleanup code) -nmake clean VCE-inlined-debug (to build the debug MSVC inlined dll with C++ exception handling) -nmake clean VSE-inlined-debug (to build the debug MSVC inlined dll with structured exception handling) -nmake clean VC-inlined-debug (to build the debug MSVC inlined dll with C cleanup code) -nmake clean VC-static-debug (to build the debug MSVC static lib with C cleanup code) - - -The pre-built dlls are normally built using the *-inlined targets. - -You can run the testsuite by changing to the "tests" directory and -running nmake. E.g.: - -$ cd tests -$ nmake - -Microsoft (R) Program Maintenance Utility Version 6.00.8168.0 -Copyright (C) Microsoft Corp 1988-1998. All rights reserved. - -Run one of the following command lines: -nmake clean VC (to test using VC dll with VC (no EH) applications) -nmake clean VCX (to test using VC dll with VC++ (EH) applications) -nmake clean VCE (to test using the VCE dll with VC++ EH applications) -nmake clean VSE (to test using VSE dll with VC (SEH) applications) -nmake clean VC-bench (to benchtest using VC dll with C bench app) -nmake clean VCX-bench (to benchtest using VC dll with C++ bench app) -nmake clean VCE-bench (to benchtest using VCE dll with C++ bench app) -nmake clean VSE-bench (to benchtest using VSE dll with SEH bench app) -nmake clean VC-static (to test using VC static lib with VC (no EH) applications) - - -Building under Mingw32 ----------------------- - -The dll can be built easily with recent versions of Mingw32. -(The distributed versions are built using Mingw32 and MsysDTK -from www.mingw32.org.) - -From the source directory, run make for help information. E.g.: - -$ make -Run one of the following command lines: -make clean GC (to build the GNU C dll with C cleanup code) -make clean GCE (to build the GNU C dll with C++ exception handling) -make clean GC-inlined (to build the GNU C inlined dll with C cleanup code) -make clean GCE-inlined (to build the GNU C inlined dll with C++ exception handling) -make clean GC-static (to build the GNU C inlined static lib with C cleanup code) -make clean GC-debug (to build the GNU C debug dll with C cleanup code) -make clean GCE-debug (to build the GNU C debug dll with C++ exception handling) -make clean GC-inlined-debug (to build the GNU C inlined debug dll with C cleanup code) -make clean GCE-inlined-debug (to build the GNU C inlined debug dll with C++ exception handling) -make clean GC-static-debug (to build the GNU C inlined static debug lib with C cleanup code) - - -The pre-built dlls are normally built using the *-inlined targets. - -You can run the testsuite by changing to the "tests" directory and -running make for help information. E.g.: - -$ cd tests -$ make -Run one of the following command lines: -make clean GC (to test using GC dll with C (no EH) applications) -make clean GCX (to test using GC dll with C++ (EH) applications) -make clean GCE (to test using GCE dll with C++ (EH) applications) -make clean GC-bench (to benchtest using GNU C dll with C cleanup code) -make clean GCE-bench (to benchtest using GNU C dll with C++ exception handling) -make clean GC-static (to test using GC static lib with C (no EH) applications) - - -Building under Linux using the Mingw32 cross development tools --------------------------------------------------------------- - -You can build the library without leaving Linux by using the Mingw32 cross -development toolchain. See http://www.libsdl.org/extras/win32/cross/ for -tools and info. The GNUmakefile contains some support for this, for example: - -make CROSS=i386-mingw32msvc- clean GC-inlined - -will build pthreadGCn.dll and libpthreadGCn.a (n=version#), provided your -cross-tools/bin directory is in your PATH (or use the cross-make.sh script -at the URL above). - - -Building the library as a statically linkable library ------------------------------------------------------ - -General: PTW32_STATIC_LIB must be defined for both the library build and the -application build. The makefiles supplied and used by the following 'make' -command lines will define this for you. - -MSVC (creates pthreadVCn.lib as a static link lib): - -nmake clean VC-static - - -MinGW32 (creates libpthreadGCn.a as a static link lib): - -make clean GC-static - - -Define PTW32_STATIC_LIB when building your application. Also, your -application must call a two non-portable routines to initialise the -some state on startup and cleanup before exit. One other routine needs -to be called to cleanup after any Win32 threads have called POSIX API -routines. See README.NONPORTABLE or the html reference manual pages for -details on these routines: - -BOOL pthread_win32_process_attach_np (void); -BOOL pthread_win32_process_detach_np (void); -BOOL pthread_win32_thread_attach_np (void); // Currently a no-op -BOOL pthread_win32_thread_detach_np (void); - - -The tests makefiles have the same targets but only check that the -static library is statically linkable. They don't run the full -testsuite. To run the full testsuite, build the dlls and run the -dll test targets. - - -Building the library under Cygwin ---------------------------------- - -Cygwin is implementing it's own POSIX threads routines and these -will be the ones to use if you develop using Cygwin. - - -Ready to run binaries ---------------------- - -For convenience, the following ready-to-run files can be downloaded -from the FTP site (see under "Availability" below): - - pthread.h - semaphore.h - sched.h - pthreadVC.dll - built with MSVC compiler using C setjmp/longjmp - pthreadVC.lib - pthreadVCE.dll - built with MSVC++ compiler using C++ EH - pthreadVCE.lib - pthreadVSE.dll - built with MSVC compiler using SEH - pthreadVSE.lib - pthreadGC.dll - built with Mingw32 GCC - libpthreadGC.a - derived from pthreadGC.dll - pthreadGCE.dll - built with Mingw32 G++ - libpthreadGCE.a - derived from pthreadGCE.dll - -As of August 2003 pthreads-win32 pthreadG* versions are built and tested -using the MinGW + MsysDTK environment current as of that date or later. -The following file MAY be needed for older MinGW environments. - - gcc.dll - needed to build and run applications that use - pthreadGCE.dll. - - -Building applications with GNU compilers ----------------------------------------- - -If you're using pthreadGC.dll: - -With the three header files, pthreadGC.dll and libpthreadGC.a in the -same directory as your application myapp.c, you could compile, link -and run myapp.c under Mingw32 as follows: - - gcc -o myapp.exe myapp.c -I. -L. -lpthreadGC - myapp - -Or put pthreadGC.dll in an appropriate directory in your PATH, -put libpthreadGC.a in your system lib directory, and -put the three header files in your system include directory, -then use: - - gcc -o myapp.exe myapp.c -lpthreadGC - myapp - - -If you're using pthreadGCE.dll: - -With the three header files, pthreadGCE.dll, gcc.dll and libpthreadGCE.a -in the same directory as your application myapp.c, you could compile, -link and run myapp.c under Mingw32 as follows: - - gcc -x c++ -o myapp.exe myapp.c -I. -L. -lpthreadGCE - myapp - -Or put pthreadGCE.dll and gcc.dll in an appropriate directory in -your PATH, put libpthreadGCE.a in your system lib directory, and -put the three header files in your system include directory, -then use: - - gcc -x c++ -o myapp.exe myapp.c -lpthreadGCE - myapp - - -Availability ------------- - -The complete source code in either unbundled, self-extracting -Zip file, or tar/gzipped format can be found at: - - ftp://sources.redhat.com/pub/pthreads-win32 - -The pre-built DLL, export libraries and matching pthread.h can -be found at: - - ftp://sources.redhat.com/pub/pthreads-win32/dll-latest - -Home page: - - http://sources.redhat.com/pthreads-win32/ - - -Mailing list ------------- - -There is a mailing list for discussing pthreads on Win32. -To join, send email to: - - pthreads-win32-subscribe@sources.redhat.com - -Unsubscribe by sending mail to: - - pthreads-win32-unsubscribe@sources.redhat.com - - -Acknowledgements ----------------- - -See the ANNOUNCE file for acknowledgements. -See the 'CONTRIBUTORS' file for the list of contributors. - -As much as possible, the ChangeLog file attributes -contributions and patches that have been incorporated -in the library to the individuals responsible. - -Finally, thanks to all those who work on and contribute to the -POSIX and Single Unix Specification standards. The maturity of an -industry can be measured by it's open standards. - ----- -Ross Johnson - - - - - - - - - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README.Borland b/bridge/third_party/quickjs/compat/win32/pthreads/README.Borland deleted file mode 100644 index a130d2bd27..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README.Borland +++ /dev/null @@ -1,57 +0,0 @@ -In ptw32_InterlockedCompareExchange.c, I've added a section for -Borland's compiler; it's identical to that for the MS compiler except -that it uses /* ... */ comments instead of ; comments. - -[RPJ: need to define HAVE_TASM32 in config.h to use the above.] - - -The other file is a makefile suitable for use with Borland's compiler -(run "make -fBmakefile" in the directory). It builds a single version -of the library, pthreadBC.dll and the corresponding pthreadBC.lib -import library, which is comparable to the pthreadVC version; I can't -personally see any demand for the versions that include structured or -C++ exception cancellation handling so I haven't attempted to build -those versions of the library. (I imagine a static version might be -of use to some, but we can't legally use that on my commercial -projects so I can't try that out, unfortunately.) - -[RPJ: Added tests\Bmakefile as well.] - -Borland C++ doesn't define the ENOSYS constant used by pthreads-win32; -rather than make more extensive patches to the pthreads-win32 source I -have a mostly-arbitrary constant for it in the makefile. However this -doesn't make it visible to the application using the library, so if -anyone actually wants to use this constant in their apps (why?) -someone might like to make a seperate NEED_BCC_something define to add -this stuff. - -The makefile also #defines EDEADLK as EDEADLOCK, _timeb as timeb, and -_ftime as ftime, to deal with the minor differences between the two -RTLs' naming conventions, and sets the compiler flags as required to -get a normal compile of the library. - -[RPJ: Moved errno values and _timeb etc to pthread.h, so apps will also -use them.] - -(While I'm on the subject, the reason Borland users should recompile -the library, rather than using the impdef/implib technique suggested -previously on the mailing list, is that a) the errno constants are -different, so the results returned by the pthread_* functions can be -meaningless, and b) the errno variable/pseudo-variable itself is -different in the MS & BCC runtimes, so you can't access the -pthreadVC's errno from a Borland C++-compiled host application -correctly - I imagine there are other potential problems from the RTL -mismatch too.) - -[RPJ: Make sure you use the same RTL in both dll and application builds. -The dll and tests Bmakefiles use cw32mti.lib. Having some trouble with -memory read exceptions running the test suite using BCC55.] - -Best regards, -Will - --- -Will Bryant -Systems Architect, eCOSM Limited -Cell +64 21 655 443, office +64 3 365 4176 -http://www.ecosm.com/ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README.CV b/bridge/third_party/quickjs/compat/win32/pthreads/README.CV deleted file mode 100644 index 698728b95b..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README.CV +++ /dev/null @@ -1,3036 +0,0 @@ -README.CV -- Condition Variables --------------------------------- - -The original implementation of condition variables in -pthreads-win32 was based on a discussion paper: - -"Strategies for Implementing POSIX Condition Variables -on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - -The changes suggested below were made on Feb 6 2001. This -file is included in the package for the benefit of anyone -interested in understanding the pthreads-win32 implementation -of condition variables and the (sometimes subtle) issues that -it attempts to resolve. - -Thanks go to the individuals whose names appear throughout -the following text. - -Ross Johnson - --------------------------------------------------------------------- - -fyi.. (more detailed problem description/demos + possible fix/patch) - -regards, -alexander. - - -Alexander Terekhov -31.01.2001 17:43 - -To: ace-bugs@cs.wustl.edu -cc: -From: Alexander Terekhov/Germany/IBM@IBMDE -Subject: Implementation of POSIX CVs: spur.wakeups/lost - signals/deadlocks/unfairness - - - - ACE VERSION: - - 5.1.12 (pthread-win32 snapshot 2000-12-29) - - HOST MACHINE and OPERATING SYSTEM: - - IBM IntelliStation Z Pro, 2 x XEON 1GHz, Win2K - - TARGET MACHINE and OPERATING SYSTEM, if different from HOST: - COMPILER NAME AND VERSION (AND PATCHLEVEL): - - Microsoft Visual C++ 6.0 - - AREA/CLASS/EXAMPLE AFFECTED: - - Implementation of POSIX condition variables - OS.cpp/.h - - DOES THE PROBLEM AFFECT: - - EXECUTION? YES! - - SYNOPSIS: - - a) spurious wakeups (minor problem) - b) lost signals - c) broadcast deadlock - d) unfairness (minor problem) - - DESCRIPTION: - - Please see attached copy of discussion thread - from comp.programming.threads for more details on - some reported problems. (i've also posted a "fyi" - message to ace-users a week or two ago but - unfortunately did not get any response so far). - - It seems that current implementation suffers from - two essential problems: - - 1) cond.waiters_count does not accurately reflect - number of waiters blocked on semaphore - w/o - proper synchronisation that could result (in the - time window when counter is not accurate) - in spurious wakeups organised by subsequent - _signals and _broadcasts. - - 2) Always having (with no e.g. copy_and_clear/..) - the same queue in use (semaphore+counter) - neither signal nor broadcast provide 'atomic' - behaviour with respect to other threads/subsequent - calls to signal/broadcast/wait. - - Each problem and combination of both could produce - various nasty things: - - a) spurious wakeups (minor problem) - - it is possible that waiter(s) which was already - unblocked even so is still counted as blocked - waiter. signal and broadcast will release - semaphore which will produce a spurious wakeup - for a 'real' waiter coming later. - - b) lost signals - - signalling thread ends up consuming its own - signal. please see demo/discussion below. - - c) broadcast deadlock - - last_waiter processing code does not correctly - handle the case with multiple threads - waiting for the end of broadcast. - please see demo/discussion below. - - d) unfairness (minor problem) - - without SignalObjectAndWait some waiter(s) - may end up consuming broadcasted signals - multiple times (spurious wakeups) because waiter - thread(s) can be preempted before they call - semaphore wait (but after count++ and mtx.unlock). - - REPEAT BY: - - See below... run problem demos programs (tennis.cpp and - tennisb.cpp) number of times concurrently (on multiprocessor) - and in multiple sessions or just add a couple of "Sleep"s - as described in the attached copy of discussion thread - from comp.programming.threads - - SAMPLE FIX/WORKAROUND: - - See attached patch to pthread-win32.. well, I can not - claim that it is completely bug free but at least my - test and tests provided by pthreads-win32 seem to work. - Perhaps that will help. - - regards, - alexander. - - ->> Forum: comp.programming.threads ->> Thread: pthread_cond_* implementation questions -. -. -. -David Schwartz wrote: - -> terekhov@my-deja.com wrote: -> ->> BTW, could you please also share your view on other perceived ->> "problems" such as nested broadcast deadlock, spurious wakeups ->> and (the latest one) lost signals?? -> ->I'm not sure what you mean. The standard allows an implementation ->to do almost whatever it likes. In fact, you could implement ->pthread_cond_wait by releasing the mutex, sleeping a random ->amount of time, and then reacquiring the mutex. Of course, ->this would be a pretty poor implementation, but any code that ->didn't work under that implementation wouldn't be strictly ->compliant. - -The implementation you suggested is indeed correct -one (yes, now I see it :). However it requires from -signal/broadcast nothing more than to "{ return 0; }" -That is not the case for pthread-win32 and ACE -implementations. I do think that these implementations -(basically the same implementation) have some serious -problems with wait/signal/broadcast calls. I am looking -for help to clarify whether these problems are real -or not. I think that I can demonstrate what I mean -using one or two small sample programs. -. -. -. -========== -tennis.cpp -========== - -#include "ace/Synch.h" -#include "ace/Thread.h" - -enum GAME_STATE { - - START_GAME, - PLAYER_A, // Player A playes the ball - PLAYER_B, // Player B playes the ball - GAME_OVER, - ONE_PLAYER_GONE, - BOTH_PLAYERS_GONE - -}; - -enum GAME_STATE eGameState; -ACE_Mutex* pmtxGameStateLock; -ACE_Condition< ACE_Mutex >* pcndGameStateChange; - -void* - playerA( - void* pParm - ) -{ - - // For access to game state variable - pmtxGameStateLock->acquire(); - - // Play loop - while ( eGameState < GAME_OVER ) { - - // Play the ball - cout << endl << "PLAYER-A" << endl; - - // Now its PLAYER-B's turn - eGameState = PLAYER_B; - - // Signal to PLAYER-B that now it is his turn - pcndGameStateChange->signal(); - - // Wait until PLAYER-B finishes playing the ball - do { - - pcndGameStateChange->wait(); - - if ( PLAYER_B == eGameState ) - cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl; - - } while ( PLAYER_B == eGameState ); - - } - - // PLAYER-A gone - eGameState = (GAME_STATE)(eGameState+1); - cout << endl << "PLAYER-A GONE" << endl; - - // No more access to state variable needed - pmtxGameStateLock->release(); - - // Signal PLAYER-A gone event - pcndGameStateChange->broadcast(); - - return 0; - -} - -void* - playerB( - void* pParm - ) -{ - - // For access to game state variable - pmtxGameStateLock->acquire(); - - // Play loop - while ( eGameState < GAME_OVER ) { - - // Play the ball - cout << endl << "PLAYER-B" << endl; - - // Now its PLAYER-A's turn - eGameState = PLAYER_A; - - // Signal to PLAYER-A that now it is his turn - pcndGameStateChange->signal(); - - // Wait until PLAYER-A finishes playing the ball - do { - - pcndGameStateChange->wait(); - - if ( PLAYER_A == eGameState ) - cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl; - - } while ( PLAYER_A == eGameState ); - - } - - // PLAYER-B gone - eGameState = (GAME_STATE)(eGameState+1); - cout << endl << "PLAYER-B GONE" << endl; - - // No more access to state variable needed - pmtxGameStateLock->release(); - - // Signal PLAYER-B gone event - pcndGameStateChange->broadcast(); - - return 0; - -} - - -int -main (int, ACE_TCHAR *[]) -{ - - pmtxGameStateLock = new ACE_Mutex(); - pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock -); - - // Set initial state - eGameState = START_GAME; - - // Create players - ACE_Thread::spawn( playerA ); - ACE_Thread::spawn( playerB ); - - // Give them 5 sec. to play - Sleep( 5000 );//sleep( 5 ); - - // Set game over state - pmtxGameStateLock->acquire(); - eGameState = GAME_OVER; - - // Let them know - pcndGameStateChange->broadcast(); - - // Wait for players to stop - do { - - pcndGameStateChange->wait(); - - } while ( eGameState < BOTH_PLAYERS_GONE ); - - // Cleanup - cout << endl << "GAME OVER" << endl; - pmtxGameStateLock->release(); - delete pcndGameStateChange; - delete pmtxGameStateLock; - - return 0; - -} - -=========== -tennisb.cpp -=========== -#include "ace/Synch.h" -#include "ace/Thread.h" - -enum GAME_STATE { - - START_GAME, - PLAYER_A, // Player A playes the ball - PLAYER_B, // Player B playes the ball - GAME_OVER, - ONE_PLAYER_GONE, - BOTH_PLAYERS_GONE - -}; - -enum GAME_STATE eGameState; -ACE_Mutex* pmtxGameStateLock; -ACE_Condition< ACE_Mutex >* pcndGameStateChange; - -void* - playerA( - void* pParm - ) -{ - - // For access to game state variable - pmtxGameStateLock->acquire(); - - // Play loop - while ( eGameState < GAME_OVER ) { - - // Play the ball - cout << endl << "PLAYER-A" << endl; - - // Now its PLAYER-B's turn - eGameState = PLAYER_B; - - // Signal to PLAYER-B that now it is his turn - pcndGameStateChange->broadcast(); - - // Wait until PLAYER-B finishes playing the ball - do { - - pcndGameStateChange->wait(); - - if ( PLAYER_B == eGameState ) - cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl; - - } while ( PLAYER_B == eGameState ); - - } - - // PLAYER-A gone - eGameState = (GAME_STATE)(eGameState+1); - cout << endl << "PLAYER-A GONE" << endl; - - // No more access to state variable needed - pmtxGameStateLock->release(); - - // Signal PLAYER-A gone event - pcndGameStateChange->broadcast(); - - return 0; - -} - -void* - playerB( - void* pParm - ) -{ - - // For access to game state variable - pmtxGameStateLock->acquire(); - - // Play loop - while ( eGameState < GAME_OVER ) { - - // Play the ball - cout << endl << "PLAYER-B" << endl; - - // Now its PLAYER-A's turn - eGameState = PLAYER_A; - - // Signal to PLAYER-A that now it is his turn - pcndGameStateChange->broadcast(); - - // Wait until PLAYER-A finishes playing the ball - do { - - pcndGameStateChange->wait(); - - if ( PLAYER_A == eGameState ) - cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl; - - } while ( PLAYER_A == eGameState ); - - } - - // PLAYER-B gone - eGameState = (GAME_STATE)(eGameState+1); - cout << endl << "PLAYER-B GONE" << endl; - - // No more access to state variable needed - pmtxGameStateLock->release(); - - // Signal PLAYER-B gone event - pcndGameStateChange->broadcast(); - - return 0; - -} - - -int -main (int, ACE_TCHAR *[]) -{ - - pmtxGameStateLock = new ACE_Mutex(); - pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock -); - - // Set initial state - eGameState = START_GAME; - - // Create players - ACE_Thread::spawn( playerA ); - ACE_Thread::spawn( playerB ); - - // Give them 5 sec. to play - Sleep( 5000 );//sleep( 5 ); - - // Make some noise - pmtxGameStateLock->acquire(); - cout << endl << "---Noise ON..." << endl; - pmtxGameStateLock->release(); - for ( int i = 0; i < 100000; i++ ) - pcndGameStateChange->broadcast(); - cout << endl << "---Noise OFF" << endl; - - // Set game over state - pmtxGameStateLock->acquire(); - eGameState = GAME_OVER; - cout << endl << "---Stopping the game..." << endl; - - // Let them know - pcndGameStateChange->broadcast(); - - // Wait for players to stop - do { - - pcndGameStateChange->wait(); - - } while ( eGameState < BOTH_PLAYERS_GONE ); - - // Cleanup - cout << endl << "GAME OVER" << endl; - pmtxGameStateLock->release(); - delete pcndGameStateChange; - delete pmtxGameStateLock; - - return 0; - -} -. -. -. -David Schwartz wrote: ->> > It's compliant ->> ->> That is really good. -> ->> Tomorrow (I have to go urgently now) I will try to ->> demonstrate the lost-signal "problem" of current ->> pthread-win32 and ACE-(variant w/o SingleObjectAndWait) ->> implementations: players start suddenly drop their balls :-) ->> (with no change in source code). -> ->Signals aren't lost, they're going to the main thread, ->which isn't coded correctly to handle them. Try this: -> -> // Wait for players to stop -> do { -> -> pthread_cond_wait( &cndGameStateChange,&mtxGameStateLock ); ->printf("Main thread stole a signal\n"); -> -> } while ( eGameState < BOTH_PLAYERS_GONE ); -> ->I bet everytime you thing a signal is lost, you'll see that printf. ->The signal isn't lost, it was stolen by another thread. - -well, you can probably loose your bet.. it was indeed stolen -by "another" thread but not the one you seem to think of. - -I think that what actually happens is the following: - -H:\SA\UXX\pt\PTHREADS\TESTS>tennis3.exe - -PLAYER-A - -PLAYER-B - -----PLAYER-B: SPURIOUS WAKEUP!!! - -PLAYER-A GONE - -PLAYER-B GONE - -GAME OVER - -H:\SA\UXX\pt\PTHREADS\TESTS> - -here you can see that PLAYER-B after playing his first -ball (which came via signal from PLAYER-A) just dropped -it down. What happened is that his signal to player A -was consumed as spurious wakeup by himself (player B). - -The implementation has a problem: - -================ -waiting threads: -================ - -{ /** Critical Section - - inc cond.waiters_count - -} - - /* - /* Atomic only if using Win32 SignalObjectAndWait - /* - cond.mtx.release - - /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX, - /*** GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE - /*** ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL! - - cond.sem.wait - -Player-A after playing game's initial ball went into -wait (called _wait) but was pre-empted before reaching -wait semaphore. He was counted as waiter but was not -actually waiting/blocked yet. - -=============== -signal threads: -=============== - -{ /** Critical Section - - waiters_count = cond.waiters_count - -} - - if ( waiters_count != 0 ) - - sem.post 1 - - endif - -Player-B after he received signal/ball from Player A -called _signal. The _signal did see that there was -one waiter blocked on the condition (Player-A) and -released the semaphore.. (but it did not unblock -Player-A because he was not actually blocked). -Player-B thread continued its execution, called _wait, -was counted as second waiter BUT was allowed to slip -through opened semaphore gate (which was opened for -Player-B) and received his own signal. Player B remained -blocked followed by Player A. Deadlock happened which -lasted until main thread came in and said game over. - -It seems to me that the implementation fails to -correctly implement the following statement -from specification: - -http://www.opengroup.org/ -onlinepubs/007908799/xsh/pthread_cond_wait.html - -"These functions atomically release mutex and cause -the calling thread to block on the condition variable -cond; atomically here means "atomically with respect -to access by another thread to the mutex and then the -condition variable". That is, if another thread is -able to acquire the mutex after the about-to-block -thread has released it, then a subsequent call to -pthread_cond_signal() or pthread_cond_broadcast() -in that thread behaves as if it were issued after -the about-to-block thread has blocked." - -Question: Am I right? - -(I produced the program output above by simply -adding ?Sleep( 1 )?: - -================ -waiting threads: -================ - -{ /** Critical Section - - inc cond.waiters_count - -} - - /* - /* Atomic only if using Win32 SignalObjectAndWait - /* - cond.mtx.release - -Sleep( 1 ); // Win32 - - /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX, - /*** GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE - /*** ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL! - - cond.sem.wait - -to the source code of pthread-win32 implementation: - -http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/ -condvar.c?rev=1.36&content-type=text/ -x-cvsweb-markup&cvsroot=pthreads-win32 - - - /* - * We keep the lock held just long enough to increment the count of - * waiters by one (above). - * Note that we can't keep it held across the - * call to sem_wait since that will deadlock other calls - * to pthread_cond_signal - */ - cleanup_args.mutexPtr = mutex; - cleanup_args.cv = cv; - cleanup_args.resultPtr = &result; - - pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) -&cleanup_args); - - if ((result = pthread_mutex_unlock (mutex)) == 0) - {((result -Sleep( 1 ); // @AT - - /* - * Wait to be awakened by - * pthread_cond_signal, or - * pthread_cond_broadcast, or - * a timeout - * - * Note: - * ptw32_sem_timedwait is a cancelation point, - * hence providing the - * mechanism for making pthread_cond_wait a cancelation - * point. We use the cleanup mechanism to ensure we - * re-lock the mutex and decrement the waiters count - * if we are canceled. - */ - if (ptw32_sem_timedwait (&(cv->sema), abstime) == -1) { - result = errno; - } - } - - pthread_cleanup_pop (1); /* Always cleanup */ - - -BTW, on my system (2 CPUs) I can manage to get -signals lost even without any source code modification -if I run the tennis program many times in different -shell sessions. -. -. -. -David Schwartz wrote: ->terekhov@my-deja.com wrote: -> ->> well, it might be that the program is in fact buggy. ->> but you did not show me any bug. -> ->You're right. I was close but not dead on. I was correct, however, ->that the code is buggy because it uses 'pthread_cond_signal' even ->though not any thread waiting on the condition variable can do the ->job. I was wrong in which thread could be waiting on the cv but ->unable to do the job. - -Okay, lets change 'pthread_cond_signal' to 'pthread_cond_broadcast' -but also add some noise from main() right before declaring the game -to be over (I need it in order to demonstrate another problem of -pthread-win32/ACE implementations - broadcast deadlock)... -. -. -. -It is my understanding of POSIX conditions, -that on correct implementation added noise -in form of unnecessary broadcasts from main, -should not break the tennis program. The -only 'side effect' of added noise on correct -implementation would be 'spurious wakeups' of -players (in fact they are not spurious, -players just see them as spurious) unblocked, -not by another player but by main before -another player had a chance to acquire the -mutex and change the game state variable: -. -. -. - -PLAYER-B - -PLAYER-A - ----Noise ON... - -PLAYER-B - -PLAYER-A - -. -. -. - -PLAYER-B - -PLAYER-A - -----PLAYER-A: SPURIOUS WAKEUP!!! - -PLAYER-B - -PLAYER-A - ----Noise OFF - -PLAYER-B - ----Stopping the game... - -PLAYER-A GONE - -PLAYER-B GONE - -GAME OVER - -H:\SA\UXX\pt\PTHREADS\TESTS> - -On pthread-win32/ACE implementations the -program could stall: - -. -. -. - -PLAYER-A - -PLAYER-B - -PLAYER-A - -PLAYER-B - -PLAYER-A - -PLAYER-B - -PLAYER-A - -PLAYER-B - ----Noise ON... - -PLAYER-A - ----Noise OFF -^C -H:\SA\UXX\pt\PTHREADS\TESTS> - - -The implementation has problems: - -================ -waiting threads: -================ - -{ /** Critical Section - - inc cond.waiters_count - -} - - /* - /* Atomic only if using Win32 SignalObjectAndWait - /* - cond.mtx.release - cond.sem.wait - - /*** ^^-- WAITER CAN BE PREEMPTED AFTER BEING UNBLOCKED... - -{ /** Critical Section - - dec cond.waiters_count - - /*** ^^- ...AND BEFORE DECREMENTING THE COUNT (1) - - last_waiter = ( cond.was_broadcast && - cond.waiters_count == 0 ) - - if ( last_waiter ) - - cond.was_broadcast = FALSE - - endif - -} - - if ( last_waiter ) - - /* - /* Atomic only if using Win32 SignalObjectAndWait - /* - cond.auto_reset_event_or_sem.post /* Event for Win32 - cond.mtx.acquire - - /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (2) - - /*** ^^-- NESTED BROADCASTS RESULT IN A DEADLOCK - - - else - - cond.mtx.acquire - - /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (3) - - endif - - -================== -broadcast threads: -================== - -{ /** Critical Section - - waiters_count = cond.waiters_count - - if ( waiters_count != 0 ) - - cond.was_broadcast = TRUE - - endif - -} - -if ( waiters_count != 0 ) - - cond.sem.post waiters_count - - /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1) - - cond.auto_reset_event_or_sem.wait /* Event for Win32 - - /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY - HAPPEN TO GO INTO WAIT WHILE PREVIOUS - BROADCAST IS STILL IN PROGRESS/WAITING - -endif - -a) cond.waiters_count does not accurately reflect -number of waiters blocked on semaphore - that could -result (in the time window when counter is not accurate) -in spurios wakeups organised by subsequent _signals -and _broadcasts. From standard compliance point of view -that is OK but that could be a real problem from -performance/efficiency point of view. - -b) If subsequent broadcast happen to go into wait on -cond.auto_reset_event_or_sem before previous -broadcast was unblocked from cond.auto_reset_event_or_sem -by its last waiter, one of two blocked threads will -remain blocked because last_waiter processing code -fails to unblock both threads. - -In the situation with tennisb.c the Player-B was put -in a deadlock by noise (broadcast) coming from main -thread. And since Player-B holds the game state -mutex when it calls broadcast, the whole program -stalled: Player-A was deadlocked on mutex and -main thread after finishing with producing the noise -was deadlocked on mutex too (needed to declare the -game over) - -(I produced the program output above by simply -adding ?Sleep( 1 )?: - -================== -broadcast threads: -================== - -{ /** Critical Section - - waiters_count = cond.waiters_count - - if ( waiters_count != 0 ) - - cond.was_broadcast = TRUE - - endif - -} - -if ( waiters_count != 0 ) - -Sleep( 1 ); //Win32 - - cond.sem.post waiters_count - - /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1) - - cond.auto_reset_event_or_sem.wait /* Event for Win32 - - /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY - HAPPEN TO GO INTO WAIT WHILE PREVIOUS - BROADCAST IS STILL IN PROGRESS/WAITING - -endif - -to the source code of pthread-win32 implementation: - -http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/ -condvar.c?rev=1.36&content-type=text/ -x-cvsweb-markup&cvsroot=pthreads-win32 - - if (wereWaiters) - {(wereWaiters)sroot=pthreads-win32eb.cgi/pthreads/Yem...m - /* - * Wake up all waiters - */ - -Sleep( 1 ); //@AT - -#ifdef NEED_SEM - - result = (ptw32_increase_semaphore( &cv->sema, cv->waiters ) - ? 0 - : EINVAL); - -#else /* NEED_SEM */ - - result = (ReleaseSemaphore( cv->sema, cv->waiters, NULL ) - ? 0 - : EINVAL); - -#endif /* NEED_SEM */ - - } - - (void) pthread_mutex_unlock(&(cv->waitersLock)); - - if (wereWaiters && result == 0) - {(wereWaiters - /* - * Wait for all the awakened threads to acquire their part of - * the counting semaphore - */ - - if (WaitForSingleObject (cv->waitersDone, INFINITE) - == WAIT_OBJECT_0) - { - result = 0; - } - else - { - result = EINVAL; - } - - } - - return (result); - -} - -BTW, on my system (2 CPUs) I can manage to get -the program stalled even without any source code -modification if I run the tennisb program many -times in different shell sessions. - -=================== -pthread-win32 patch -=================== -struct pthread_cond_t_ { - long nWaitersBlocked; /* Number of threads blocked -*/ - long nWaitersUnblocked; /* Number of threads unblocked -*/ - long nWaitersToUnblock; /* Number of threads to unblock -*/ - sem_t semBlockQueue; /* Queue up threads waiting for the -*/ - /* condition to become signalled -*/ - sem_t semBlockLock; /* Semaphore that guards access to -*/ - /* | waiters blocked count/block queue -*/ - /* +-> Mandatory Sync.LEVEL-1 -*/ - pthread_mutex_t mtxUnblockLock; /* Mutex that guards access to -*/ - /* | waiters (to)unblock(ed) counts -*/ - /* +-> Optional* Sync.LEVEL-2 -*/ -}; /* Opt*) for _timedwait and -cancellation*/ - -int -pthread_cond_init (pthread_cond_t * cond, const pthread_condattr_t * attr) - int result = EAGAIN; - pthread_cond_t cv = NULL; - - if (cond == NULL) - {(cond - return EINVAL; - } - - if ((attr != NULL && *attr != NULL) && - ((*attr)->pshared == PTHREAD_PROCESS_SHARED)) - { - /* - * Creating condition variable that can be shared between - * processes. - */ - result = ENOSYS; - - goto FAIL0; - } - - cv = (pthread_cond_t) calloc (1, sizeof (*cv)); - - if (cv == NULL) - {(cv - result = ENOMEM; - goto FAIL0; - } - - cv->nWaitersBlocked = 0; - cv->nWaitersUnblocked = 0; - cv->nWaitersToUnblock = 0; - - if (sem_init (&(cv->semBlockLock), 0, 1) != 0) - {(sem_init - goto FAIL0; - } - - if (sem_init (&(cv->semBlockQueue), 0, 0) != 0) - {(sem_init - goto FAIL1; - } - - if (pthread_mutex_init (&(cv->mtxUnblockLock), 0) != 0) - {(pthread_mutex_init - goto FAIL2; - } - - - result = 0; - - goto DONE; - - /* - * ------------- - * Failed... - * ------------- - */ -FAIL2: - (void) sem_destroy (&(cv->semBlockQueue)); - -FAIL1: - (void) sem_destroy (&(cv->semBlockLock)); - -FAIL0: -DONE: - *cond = cv; - - return (result); - -} /* pthread_cond_init */ - -int -pthread_cond_destroy (pthread_cond_t * cond) -{ - int result = 0; - pthread_cond_t cv; - - /* - * Assuming any race condition here is harmless. - */ - if (cond == NULL - || *cond == NULL) - { - return EINVAL; - } - - if (*cond != (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) - {(*cond - cv = *cond; - - /* - * Synchronize access to waiters blocked count (LEVEL-1) - */ - if (sem_wait(&(cv->semBlockLock)) != 0) - {(sem_wait(&(cv->semBlockLock)) - return errno; - } - - /* - * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2) - */ - if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) - {((result - (void) sem_post(&(cv->semBlockLock)); - return result; - } - - /* - * Check whether cv is still busy (still has waiters blocked) - */ - if (cv->nWaitersBlocked - cv->nWaitersUnblocked > 0) - {(cv->nWaitersBlocked - (void) sem_post(&(cv->semBlockLock)); - (void) pthread_mutex_unlock(&(cv->mtxUnblockLock)); - return EBUSY; - } - - /* - * Now it is safe to destroy - */ - (void) sem_destroy (&(cv->semBlockLock)); - (void) sem_destroy (&(cv->semBlockQueue)); - (void) pthread_mutex_unlock (&(cv->mtxUnblockLock)); - (void) pthread_mutex_destroy (&(cv->mtxUnblockLock)); - - free(cv); - *cond = NULL; - } - else - { - /* - * See notes in ptw32_cond_check_need_init() above also. - */ - EnterCriticalSection(&ptw32_cond_test_init_lock); - - /* - * Check again. - */ - if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) - {(*cond - /* - * This is all we need to do to destroy a statically - * initialised cond that has not yet been used (initialised). - * If we get to here, another thread - * waiting to initialise this cond will get an EINVAL. - */ - *cond = NULL; - } - else - { - /* - * The cv has been initialised while we were waiting - * so assume it's in use. - */ - result = EBUSY; - } - - LeaveCriticalSection(&ptw32_cond_test_init_lock); - } - - return (result); -} - -/* - * Arguments for cond_wait_cleanup, since we can only pass a - * single void * to it. - */ -typedef struct { - pthread_mutex_t * mutexPtr; - pthread_cond_t cv; - int * resultPtr; -} ptw32_cond_wait_cleanup_args_t; - -static void -ptw32_cond_wait_cleanup(void * args) -{ - ptw32_cond_wait_cleanup_args_t * cleanup_args = -(ptw32_cond_wait_cleanup_args_t *) args; - pthread_cond_t cv = cleanup_args->cv; - int * resultPtr = cleanup_args->resultPtr; - int eLastSignal; /* enum: 1=yes 0=no -1=cancelled/timedout w/o signal(s) -*/ - int result; - - /* - * Whether we got here as a result of signal/broadcast or because of - * timeout on wait or thread cancellation we indicate that we are no - * longer waiting. The waiter is responsible for adjusting waiters - * (to)unblock(ed) counts (protected by unblock lock). - * Unblock lock/Sync.LEVEL-2 supports _timedwait and cancellation. - */ - if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) - {((result - *resultPtr = result; - return; - } - - cv->nWaitersUnblocked++; - - eLastSignal = (cv->nWaitersToUnblock == 0) ? - -1 : (--cv->nWaitersToUnblock == 0); - - /* - * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed - */ - if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0) - {((result - *resultPtr = result; - return; - } - - /* - * If last signal... - */ - if (eLastSignal == 1) - {(eLastSignal - /* - * ...it means that we have end of 'atomic' signal/broadcast - */ - if (sem_post(&(cv->semBlockLock)) != 0) - {(sem_post(&(cv->semBlockLock)) - *resultPtr = errno; - return; - } - } - /* - * If not last signal and not timed out/cancelled wait w/o signal... - */ - else if (eLastSignal == 0) - { - /* - * ...it means that next waiter can go through semaphore - */ - if (sem_post(&(cv->semBlockQueue)) != 0) - {(sem_post(&(cv->semBlockQueue)) - *resultPtr = errno; - return; - } - } - - /* - * XSH: Upon successful return, the mutex has been locked and is owned - * by the calling thread - */ - if ((result = pthread_mutex_lock(cleanup_args->mutexPtr)) != 0) - {((result - *resultPtr = result; - } - -} /* ptw32_cond_wait_cleanup */ - -static int -ptw32_cond_timedwait (pthread_cond_t * cond, - pthread_mutex_t * mutex, - const struct timespec *abstime) -{ - int result = 0; - pthread_cond_t cv; - ptw32_cond_wait_cleanup_args_t cleanup_args; - - if (cond == NULL || *cond == NULL) - {(cond - return EINVAL; - } - - /* - * We do a quick check to see if we need to do more work - * to initialise a static condition variable. We check - * again inside the guarded section of ptw32_cond_check_need_init() - * to avoid race conditions. - */ - if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) - {(*cond - result = ptw32_cond_check_need_init(cond); - } - - if (result != 0 && result != EBUSY) - {(result - return result; - } - - cv = *cond; - - /* - * Synchronize access to waiters blocked count (LEVEL-1) - */ - if (sem_wait(&(cv->semBlockLock)) != 0) - {(sem_wait(&(cv->semBlockLock)) - return errno; - } - - cv->nWaitersBlocked++; - - /* - * Thats it. Counted means waiting, no more access needed - */ - if (sem_post(&(cv->semBlockLock)) != 0) - {(sem_post(&(cv->semBlockLock)) - return errno; - } - - /* - * Setup this waiter cleanup handler - */ - cleanup_args.mutexPtr = mutex; - cleanup_args.cv = cv; - cleanup_args.resultPtr = &result; - - pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) &cleanup_args); - - /* - * Now we can release 'mutex' and... - */ - if ((result = pthread_mutex_unlock (mutex)) == 0) - {((result - - /* - * ...wait to be awakened by - * pthread_cond_signal, or - * pthread_cond_broadcast, or - * timeout, or - * thread cancellation - * - * Note: - * - * ptw32_sem_timedwait is a cancellation point, - * hence providing the mechanism for making - * pthread_cond_wait a cancellation point. - * We use the cleanup mechanism to ensure we - * re-lock the mutex and adjust (to)unblock(ed) waiters - * counts if we are cancelled, timed out or signalled. - */ - if (ptw32_sem_timedwait (&(cv->semBlockQueue), abstime) != 0) - {(ptw32_sem_timedwait - result = errno; - } - } - - /* - * Always cleanup - */ - pthread_cleanup_pop (1); - - - /* - * "result" can be modified by the cleanup handler. - */ - return (result); - -} /* ptw32_cond_timedwait */ - - -static int -ptw32_cond_unblock (pthread_cond_t * cond, - int unblockAll) -{ - int result; - pthread_cond_t cv; - - if (cond == NULL || *cond == NULL) - {(cond - return EINVAL; - } - - cv = *cond; - - /* - * No-op if the CV is static and hasn't been initialised yet. - * Assuming that any race condition is harmless. - */ - if (cv == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) - {(cv - return 0; - } - - /* - * Synchronize access to waiters blocked count (LEVEL-1) - */ - if (sem_wait(&(cv->semBlockLock)) != 0) - {(sem_wait(&(cv->semBlockLock)) - return errno; - } - - /* - * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2) - * This sync.level supports _timedwait and cancellation - */ - if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) - {((result - return result; - } - - /* - * Adjust waiters blocked and unblocked counts (collect garbage) - */ - if (cv->nWaitersUnblocked != 0) - {(cv->nWaitersUnblocked - cv->nWaitersBlocked -= cv->nWaitersUnblocked; - cv->nWaitersUnblocked = 0; - } - - /* - * If (after adjustment) there are still some waiters blocked counted... - */ - if ( cv->nWaitersBlocked > 0) - {( - /* - * We will unblock first waiter and leave semBlockLock/LEVEL-1 locked - * LEVEL-1 access is left disabled until last signal/unblock -completes - */ - cv->nWaitersToUnblock = (unblockAll) ? cv->nWaitersBlocked : 1; - - /* - * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed - * This sync.level supports _timedwait and cancellation - */ - if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0) - {((result - return result; - } - - - /* - * Now, with LEVEL-2 lock released let first waiter go through -semaphore - */ - if (sem_post(&(cv->semBlockQueue)) != 0) - {(sem_post(&(cv->semBlockQueue)) - return errno; - } - } - /* - * No waiter blocked - no more LEVEL-1 access to blocked count needed... - */ - else if (sem_post(&(cv->semBlockLock)) != 0) - { - return errno; - } - /* - * ...and no more LEVEL-2 access to waiters (to)unblock(ed) counts needed -too - * This sync.level supports _timedwait and cancellation - */ - else - { - result = pthread_mutex_unlock(&(cv->mtxUnblockLock)); - } - - return(result); - -} /* ptw32_cond_unblock */ - -int -pthread_cond_wait (pthread_cond_t * cond, - pthread_mutex_t * mutex) -{ - /* The NULL abstime arg means INFINITE waiting. */ - return(ptw32_cond_timedwait(cond, mutex, NULL)); -} /* pthread_cond_wait */ - - -int -pthread_cond_timedwait (pthread_cond_t * cond, - pthread_mutex_t * mutex, - const struct timespec *abstime) -{ - if (abstime == NULL) - {(abstime - return EINVAL; - } - - return(ptw32_cond_timedwait(cond, mutex, abstime)); -} /* pthread_cond_timedwait */ - - -int -pthread_cond_signal (pthread_cond_t * cond) -{ - /* The '0'(FALSE) unblockAll arg means unblock ONE waiter. */ - return(ptw32_cond_unblock(cond, 0)); -} /* pthread_cond_signal */ - -int -pthread_cond_broadcast (pthread_cond_t * cond) -{ - /* The '1'(TRUE) unblockAll arg means unblock ALL waiters. */ - return(ptw32_cond_unblock(cond, 1)); -} /* pthread_cond_broadcast */ - - - - -TEREKHOV@de.ibm.com on 17.01.2001 01:00:57 - -Please respond to TEREKHOV@de.ibm.com - -To: pthreads-win32@sourceware.cygnus.com -cc: schmidt@uci.edu -Subject: win32 conditions: sem+counter+event = broadcast_deadlock + - spur.wakeup/unfairness/incorrectness ?? - - - - - - - -Hi, - -Problem 1: broadcast_deadlock - -It seems that current implementation does not provide "atomic" -broadcasts. That may lead to "nested" broadcasts... and it seems -that nested case is not handled correctly -> producing a broadcast -DEADLOCK as a result. - -Scenario: - -N (>1) waiting threads W1..N are blocked (in _wait) on condition's -semaphore. - -Thread B1 calls pthread_cond_broadcast, which results in "releasing" N -W threads via incrementing semaphore counter by N (stored in -cv->waiters) BUT cv->waiters counter does not change!! The caller -thread B1 remains blocked on cv->waitersDone event (auto-reset!!) BUT -condition is not protected from starting another broadcast (when called -on another thread) while still waiting for the "old" broadcast to -complete on thread B1. - -M (>=0, waiters counter. - -L (N-M) "late" waiter W threads are a) still blocked/not returned from -their semaphore wait call or b) were preempted after sem_wait but before -lock( &cv->waitersLock ) or c) are blocked on cv->waitersLock. - -cv->waiters is still > 0 (= L). - -Another thread B2 (or some W thread from M group) calls -pthread_cond_broadcast and gains access to counter... neither a) nor b) -prevent thread B2 in pthread_cond_broadcast from gaining access to -counter and starting another broadcast ( for c) - it depends on -cv->waitersLock scheduling rules: FIFO=OK, PRTY=PROBLEM,... ) - -That call to pthread_cond_broadcast (on thread B2) will result in -incrementing semaphore by cv->waiters (=L) which is INCORRECT (all -W1..N were in fact already released by thread B1) and waiting on -_auto-reset_ event cv->waitersDone which is DEADLY WRONG (produces a -deadlock)... - -All late W1..L threads now have a chance to complete their _wait call. -Last W_L thread sets an auto-reselt event cv->waitersDone which will -release either B1 or B2 leaving one of B threads in a deadlock. - -Problem 2: spur.wakeup/unfairness/incorrectness - -It seems that: - -a) because of the same problem with counter which does not reflect the -actual number of NOT RELEASED waiters, the signal call may increment -a semaphore counter w/o having a waiter blocked on it. That will result -in (best case) spurious wake ups - performance degradation due to -unnecessary context switches and predicate re-checks and (in worth case) -unfairness/incorrectness problem - see b) - -b) neither signal nor broadcast prevent other threads - "new waiters" -(and in the case of signal, the caller thread as well) from going into -_wait and overtaking "old" waiters (already released but still not returned -from sem_wait on condition's semaphore). Win semaphore just [API DOC]: -"Maintains a count between zero and some maximum value, limiting the number -of threads that are simultaneously accessing a shared resource." Calling -ReleaseSemaphore does not imply (at least not documented) that on return -from ReleaseSemaphore all waiters will in fact become released (returned -from their Wait... call) and/or that new waiters calling Wait... afterwards -will become less importance. It is NOT documented to be an atomic release -of -waiters... And even if it would be there is still a problem with a thread -being preempted after Wait on semaphore and before Wait on cv->waitersLock -and scheduling rules for cv->waitersLock itself -(??WaitForMultipleObjects??) -That may result in unfairness/incorrectness problem as described -for SetEvent impl. in "Strategies for Implementing POSIX Condition -Variables -on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - -Unfairness -- The semantics of the POSIX pthread_cond_broadcast function is -to wake up all threads currently blocked in wait calls on the condition -variable. The awakened threads then compete for the external_mutex. To -ensure -fairness, all of these threads should be released from their -pthread_cond_wait calls and allowed to recheck their condition expressions -before other threads can successfully complete a wait on the condition -variable. - -Unfortunately, the SetEvent implementation above does not guarantee that -all -threads sleeping on the condition variable when cond_broadcast is called -will -acquire the external_mutex and check their condition expressions. Although -the Pthreads specification does not mandate this degree of fairness, the -lack of fairness can cause starvation. - -To illustrate the unfairness problem, imagine there are 2 threads, C1 and -C2, -that are blocked in pthread_cond_wait on condition variable not_empty_ that -is guarding a thread-safe message queue. Another thread, P1 then places two -messages onto the queue and calls pthread_cond_broadcast. If C1 returns -from -pthread_cond_wait, dequeues and processes the message, and immediately -waits -again then it and only it may end up acquiring both messages. Thus, C2 will -never get a chance to dequeue a message and run. - -The following illustrates the sequence of events: - -1. Thread C1 attempts to dequeue and waits on CV non_empty_ -2. Thread C2 attempts to dequeue and waits on CV non_empty_ -3. Thread P1 enqueues 2 messages and broadcasts to CV not_empty_ -4. Thread P1 exits -5. Thread C1 wakes up from CV not_empty_, dequeues a message and runs -6. Thread C1 waits again on CV not_empty_, immediately dequeues the 2nd - message and runs -7. Thread C1 exits -8. Thread C2 is the only thread left and blocks forever since - not_empty_ will never be signaled - -Depending on the algorithm being implemented, this lack of fairness may -yield -concurrent programs that have subtle bugs. Of course, application -developers -should not rely on the fairness semantics of pthread_cond_broadcast. -However, -there are many cases where fair implementations of condition variables can -simplify application code. - -Incorrectness -- A variation on the unfairness problem described above -occurs -when a third consumer thread, C3, is allowed to slip through even though it -was not waiting on condition variable not_empty_ when a broadcast occurred. - -To illustrate this, we will use the same scenario as above: 2 threads, C1 -and -C2, are blocked dequeuing messages from the message queue. Another thread, -P1 -then places two messages onto the queue and calls pthread_cond_broadcast. -C1 -returns from pthread_cond_wait, dequeues and processes the message. At this -time, C3 acquires the external_mutex, calls pthread_cond_wait and waits on -the events in WaitForMultipleObjects. Since C2 has not had a chance to run -yet, the BROADCAST event is still signaled. C3 then returns from -WaitForMultipleObjects, and dequeues and processes the message in the -queue. -Thus, C2 will never get a chance to dequeue a message and run. - -The following illustrates the sequence of events: - -1. Thread C1 attempts to dequeue and waits on CV non_empty_ -2. Thread C2 attempts to dequeue and waits on CV non_empty_ -3. Thread P1 enqueues 2 messages and broadcasts to CV not_empty_ -4. Thread P1 exits -5. Thread C1 wakes up from CV not_empty_, dequeues a message and runs -6. Thread C1 exits -7. Thread C3 waits on CV not_empty_, immediately dequeues the 2nd - message and runs -8. Thread C3 exits -9. Thread C2 is the only thread left and blocks forever since - not_empty_ will never be signaled - -In the above case, a thread that was not waiting on the condition variable -when a broadcast occurred was allowed to proceed. This leads to incorrect -semantics for a condition variable. - - -COMMENTS??? - -regards, -alexander. - ------------------------------------------------------------------------------ - -Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* - implementation questions -Date: Wed, 21 Feb 2001 11:54:47 +0100 -From: TEREKHOV@de.ibm.com -To: lthomas@arbitrade.com -CC: rpj@ise.canberra.edu.au, Thomas Pfaff , - Nanbor Wang - -Hi Louis, - -generation number 8.. - -had some time to revisit timeouts/spurious wakeup problem.. -found some bugs (in 7.b/c/d) and something to improve -(7a - using IPC semaphores but it should speedup Win32 -version as well). - -regards, -alexander. - ----------- Algorithm 8a / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ -given: -semBlockLock - bin.semaphore -semBlockQueue - semaphore -mtxExternal - mutex or CS -mtxUnblockLock - mutex or CS -nWaitersGone - int -nWaitersBlocked - int -nWaitersToUnblock - int - -wait( timeout ) { - - [auto: register int result ] // error checking omitted - [auto: register int nSignalsWasLeft ] - [auto: register int nWaitersWasGone ] - - sem_wait( semBlockLock ); - nWaitersBlocked++; - sem_post( semBlockLock ); - - unlock( mtxExternal ); - bTimedOut = sem_wait( semBlockQueue,timeout ); - - lock( mtxUnblockLock ); - if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { - if ( bTimeout ) { // timeout (or canceled) - if ( 0 != nWaitersBlocked ) { - nWaitersBlocked--; - } - else { - nWaitersGone++; // count spurious wakeups - } - } - if ( 0 == --nWaitersToUnblock ) { - if ( 0 != nWaitersBlocked ) { - sem_post( semBlockLock ); // open the gate - nSignalsWasLeft = 0; // do not open the gate below -again - } - else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { - nWaitersGone = 0; - } - } - } - else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious -semaphore :-) - sem_wait( semBlockLock ); - nWaitersBlocked -= nWaitersGone; // something is going on here - -test of timeouts? :-) - sem_post( semBlockLock ); - nWaitersGone = 0; - } - unlock( mtxUnblockLock ); - - if ( 1 == nSignalsWasLeft ) { - if ( 0 != nWaitersWasGone ) { - // sem_adjust( -nWaitersWasGone ); - while ( nWaitersWasGone-- ) { - sem_wait( semBlockLock ); // better now than spurious -later - } - } - sem_post( semBlockLock ); // open the gate - } - - lock( mtxExternal ); - - return ( bTimedOut ) ? ETIMEOUT : 0; -} - -signal(bAll) { - - [auto: register int result ] - [auto: register int nSignalsToIssue] - - lock( mtxUnblockLock ); - - if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! - if ( 0 == nWaitersBlocked ) { // NO-OP - return unlock( mtxUnblockLock ); - } - if (bAll) { - nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nSignalsToIssue = 1; - nWaitersToUnblock++; - nWaitersBlocked--; - } - } - else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! - sem_wait( semBlockLock ); // close the gate - if ( 0 != nWaitersGone ) { - nWaitersBlocked -= nWaitersGone; - nWaitersGone = 0; - } - if (bAll) { - nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nSignalsToIssue = nWaitersToUnblock = 1; - nWaitersBlocked--; - } - } - else { // NO-OP - return unlock( mtxUnblockLock ); - } - - unlock( mtxUnblockLock ); - sem_post( semBlockQueue,nSignalsToIssue ); - return result; -} - ----------- Algorithm 8b / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE ------- -given: -semBlockLock - bin.semaphore -semBlockQueue - bin.semaphore -mtxExternal - mutex or CS -mtxUnblockLock - mutex or CS -nWaitersGone - int -nWaitersBlocked - int -nWaitersToUnblock - int - -wait( timeout ) { - - [auto: register int result ] // error checking omitted - [auto: register int nWaitersWasGone ] - [auto: register int nSignalsWasLeft ] - - sem_wait( semBlockLock ); - nWaitersBlocked++; - sem_post( semBlockLock ); - - unlock( mtxExternal ); - bTimedOut = sem_wait( semBlockQueue,timeout ); - - lock( mtxUnblockLock ); - if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { - if ( bTimeout ) { // timeout (or canceled) - if ( 0 != nWaitersBlocked ) { - nWaitersBlocked--; - nSignalsWasLeft = 0; // do not unblock next waiter -below (already unblocked) - } - else { - nWaitersGone = 1; // spurious wakeup pending!! - } - } - if ( 0 == --nWaitersToUnblock && - if ( 0 != nWaitersBlocked ) { - sem_post( semBlockLock ); // open the gate - nSignalsWasLeft = 0; // do not open the gate below -again - } - else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { - nWaitersGone = 0; - } - } - } - else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious -semaphore :-) - sem_wait( semBlockLock ); - nWaitersBlocked -= nWaitersGone; // something is going on here - -test of timeouts? :-) - sem_post( semBlockLock ); - nWaitersGone = 0; - } - unlock( mtxUnblockLock ); - - if ( 1 == nSignalsWasLeft ) { - if ( 0 != nWaitersWasGone ) { - // sem_adjust( -1 ); - sem_wait( semBlockQueue ); // better now than spurious -later - } - sem_post( semBlockLock ); // open the gate - } - else if ( 0 != nSignalsWasLeft ) { - sem_post( semBlockQueue ); // unblock next waiter - } - - lock( mtxExternal ); - - return ( bTimedOut ) ? ETIMEOUT : 0; -} - -signal(bAll) { - - [auto: register int result ] - - lock( mtxUnblockLock ); - - if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! - if ( 0 == nWaitersBlocked ) { // NO-OP - return unlock( mtxUnblockLock ); - } - if (bAll) { - nWaitersToUnblock += nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nWaitersToUnblock++; - nWaitersBlocked--; - } - unlock( mtxUnblockLock ); - } - else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! - sem_wait( semBlockLock ); // close the gate - if ( 0 != nWaitersGone ) { - nWaitersBlocked -= nWaitersGone; - nWaitersGone = 0; - } - if (bAll) { - nWaitersToUnblock = nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nWaitersToUnblock = 1; - nWaitersBlocked--; - } - unlock( mtxUnblockLock ); - sem_post( semBlockQueue ); - } - else { // NO-OP - unlock( mtxUnblockLock ); - } - - return result; -} - ----------- Algorithm 8c / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE ---------- -given: -hevBlockLock - auto-reset event -hevBlockQueue - auto-reset event -mtxExternal - mutex or CS -mtxUnblockLock - mutex or CS -nWaitersGone - int -nWaitersBlocked - int -nWaitersToUnblock - int - -wait( timeout ) { - - [auto: register int result ] // error checking omitted - [auto: register int nSignalsWasLeft ] - [auto: register int nWaitersWasGone ] - - wait( hevBlockLock,INFINITE ); - nWaitersBlocked++; - set_event( hevBlockLock ); - - unlock( mtxExternal ); - bTimedOut = wait( hevBlockQueue,timeout ); - - lock( mtxUnblockLock ); - if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { - if ( bTimeout ) { // timeout (or canceled) - if ( 0 != nWaitersBlocked ) { - nWaitersBlocked--; - nSignalsWasLeft = 0; // do not unblock next waiter -below (already unblocked) - } - else { - nWaitersGone = 1; // spurious wakeup pending!! - } - } - if ( 0 == --nWaitersToUnblock ) - if ( 0 != nWaitersBlocked ) { - set_event( hevBlockLock ); // open the gate - nSignalsWasLeft = 0; // do not open the gate below -again - } - else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { - nWaitersGone = 0; - } - } - } - else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious -event :-) - wait( hevBlockLock,INFINITE ); - nWaitersBlocked -= nWaitersGone; // something is going on here - -test of timeouts? :-) - set_event( hevBlockLock ); - nWaitersGone = 0; - } - unlock( mtxUnblockLock ); - - if ( 1 == nSignalsWasLeft ) { - if ( 0 != nWaitersWasGone ) { - reset_event( hevBlockQueue ); // better now than spurious -later - } - set_event( hevBlockLock ); // open the gate - } - else if ( 0 != nSignalsWasLeft ) { - set_event( hevBlockQueue ); // unblock next waiter - } - - lock( mtxExternal ); - - return ( bTimedOut ) ? ETIMEOUT : 0; -} - -signal(bAll) { - - [auto: register int result ] - - lock( mtxUnblockLock ); - - if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! - if ( 0 == nWaitersBlocked ) { // NO-OP - return unlock( mtxUnblockLock ); - } - if (bAll) { - nWaitersToUnblock += nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nWaitersToUnblock++; - nWaitersBlocked--; - } - unlock( mtxUnblockLock ); - } - else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! - wait( hevBlockLock,INFINITE ); // close the gate - if ( 0 != nWaitersGone ) { - nWaitersBlocked -= nWaitersGone; - nWaitersGone = 0; - } - if (bAll) { - nWaitersToUnblock = nWaitersBlocked; - nWaitersBlocked = 0; - } - else { - nWaitersToUnblock = 1; - nWaitersBlocked--; - } - unlock( mtxUnblockLock ); - set_event( hevBlockQueue ); - } - else { // NO-OP - unlock( mtxUnblockLock ); - } - - return result; -} - ----------- Algorithm 8d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ -given: -hevBlockLock - auto-reset event -hevBlockQueueS - auto-reset event // for signals -hevBlockQueueB - manual-reset even // for broadcasts -mtxExternal - mutex or CS -mtxUnblockLock - mutex or CS -eBroadcast - int // 0: no broadcast, 1: broadcast, 2: -broadcast after signal(s) -nWaitersGone - int -nWaitersBlocked - int -nWaitersToUnblock - int - -wait( timeout ) { - - [auto: register int result ] // error checking omitted - [auto: register int eWasBroadcast ] - [auto: register int nSignalsWasLeft ] - [auto: register int nWaitersWasGone ] - - wait( hevBlockLock,INFINITE ); - nWaitersBlocked++; - set_event( hevBlockLock ); - - unlock( mtxExternal ); - bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE ); - - lock( mtxUnblockLock ); - if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { - if ( bTimeout ) { // timeout (or canceled) - if ( 0 != nWaitersBlocked ) { - nWaitersBlocked--; - nSignalsWasLeft = 0; // do not unblock next waiter -below (already unblocked) - } - else if ( 1 != eBroadcast ) { - nWaitersGone = 1; - } - } - if ( 0 == --nWaitersToUnblock ) { - if ( 0 != nWaitersBlocked ) { - set_event( hevBlockLock ); // open the gate - nSignalsWasLeft = 0; // do not open the gate below -again - } - else { - if ( 0 != (eWasBroadcast = eBroadcast) ) { - eBroadcast = 0; - } - if ( 0 != (nWaitersWasGone = nWaitersGone ) { - nWaitersGone = 0; - } - } - } - else if ( 0 != eBroadcast ) { - nSignalsWasLeft = 0; // do not unblock next waiter -below (already unblocked) - } - } - else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious -event :-) - wait( hevBlockLock,INFINITE ); - nWaitersBlocked -= nWaitersGone; // something is going on here - -test of timeouts? :-) - set_event( hevBlockLock ); - nWaitersGone = 0; - } - unlock( mtxUnblockLock ); - - if ( 1 == nSignalsWasLeft ) { - if ( 0 != eWasBroadcast ) { - reset_event( hevBlockQueueB ); - } - if ( 0 != nWaitersWasGone ) { - reset_event( hevBlockQueueS ); // better now than spurious -later - } - set_event( hevBlockLock ); // open the gate - } - else if ( 0 != nSignalsWasLeft ) { - set_event( hevBlockQueueS ); // unblock next waiter - } - - lock( mtxExternal ); - - return ( bTimedOut ) ? ETIMEOUT : 0; -} - -signal(bAll) { - - [auto: register int result ] - [auto: register HANDLE hevBlockQueue ] - - lock( mtxUnblockLock ); - - if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! - if ( 0 == nWaitersBlocked ) { // NO-OP - return unlock( mtxUnblockLock ); - } - if (bAll) { - nWaitersToUnblock += nWaitersBlocked; - nWaitersBlocked = 0; - eBroadcast = 2; - hevBlockQueue = hevBlockQueueB; - } - else { - nWaitersToUnblock++; - nWaitersBlocked--; - return unlock( mtxUnblockLock ); - } - } - else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! - wait( hevBlockLock,INFINITE ); // close the gate - if ( 0 != nWaitersGone ) { - nWaitersBlocked -= nWaitersGone; - nWaitersGone = 0; - } - if (bAll) { - nWaitersToUnblock = nWaitersBlocked; - nWaitersBlocked = 0; - eBroadcast = 1; - hevBlockQueue = hevBlockQueueB; - } - else { - nWaitersToUnblock = 1; - nWaitersBlocked--; - hevBlockQueue = hevBlockQueueS; - } - } - else { // NO-OP - return unlock( mtxUnblockLock ); - } - - unlock( mtxUnblockLock ); - set_event( hevBlockQueue ); - return result; -} ----------------------- Forwarded by Alexander Terekhov/Germany/IBM on -02/21/2001 09:13 AM --------------------------- - -Alexander Terekhov -02/20/2001 04:33 PM - -To: Louis Thomas -cc: - -From: Alexander Terekhov/Germany/IBM@IBMDE -Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio - n questions -Importance: Normal - ->Sorry, gotta take a break and work on something else for a while. ->Real work ->calls, unfortunately. I'll get back to you in two or three days. - -ok. no problem. here is some more stuff for pauses you might have -in between :) - ----------- Algorithm 7d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ -given: -hevBlockLock - auto-reset event -hevBlockQueueS - auto-reset event // for signals -hevBlockQueueB - manual-reset even // for broadcasts -mtxExternal - mutex or CS -mtxUnblockLock - mutex or CS -bBroadcast - int -nWaitersGone - int -nWaitersBlocked - int -nWaitersToUnblock - int - -wait( timeout ) { - - [auto: register int result ] // error checking omitted - [auto: register int bWasBroadcast ] - [auto: register int nSignalsWasLeft ] - - wait( hevBlockLock,INFINITE ); - nWaitersBlocked++; - set_event( hevBlockLock ); - - unlock( mtxExternal ); - bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE ); - - lock( mtxUnblockLock ); - if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { - if ( bTimeout ) { // timeout (or canceled) - if ( 0 != nWaitersBlocked ) { - nWaitersBlocked--; - nSignalsWasLeft = 0; // do not unblock next waiter -below (already unblocked) - } - else if ( !bBroadcast ) { - wait( hevBlockQueueS,INFINITE ); // better now than spurious -later - } - } - if ( 0 == --nWaitersToUnblock ) { - if ( 0 != nWaitersBlocked ) { - if ( bBroadcast ) { - reset_event( hevBlockQueueB ); - bBroadcast = false; - } - set_event( hevBlockLock ); // open the gate - nSignalsWasLeft = 0; // do not open the gate below -again - } - else if ( false != (bWasBroadcast = bBroadcast) ) { - bBroadcast = false; - } - } - else { - bWasBroadcast = bBroadcast; - } - } - else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious -event :-) - wait( hevBlockLock,INFINITE ); - nWaitersBlocked -= nWaitersGone; // something is going on here - -test of timeouts? :-) - set_event( hevBlockLock ); - nWaitersGone = 0; - } - unlock( mtxUnblockLock ); - - if ( 1 == nSignalsWasLeft ) { - if ( bWasBroadcast ) { - reset_event( hevBlockQueueB ); - } - set_event( hevBlockLock ); // open the gate - } - else if ( 0 != nSignalsWasLeft && !bWasBroadcast ) { - set_event( hevBlockQueueS ); // unblock next waiter - } - - lock( mtxExternal ); - - return ( bTimedOut ) ? ETIMEOUT : 0; -} - -signal(bAll) { - - [auto: register int result ] - [auto: register HANDLE hevBlockQueue ] - - lock( mtxUnblockLock ); - - if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! - if ( 0 == nWaitersBlocked ) { // NO-OP - return unlock( mtxUnblockLock ); - } - if (bAll) { - nWaitersToUnblock += nWaitersBlocked; - nWaitersBlocked = 0; - bBroadcast = true; - hevBlockQueue = hevBlockQueueB; - } - else { - nWaitersToUnblock++; - nWaitersBlocked--; - return unlock( mtxUnblockLock ); - } - } - else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! - wait( hevBlockLock,INFINITE ); // close the gate - if ( 0 != nWaitersGone ) { - nWaitersBlocked -= nWaitersGone; - nWaitersGone = 0; - } - if (bAll) { - nWaitersToUnblock = nWaitersBlocked; - nWaitersBlocked = 0; - bBroadcast = true; - hevBlockQueue = hevBlockQueueB; - } - else { - nWaitersToUnblock = 1; - nWaitersBlocked--; - hevBlockQueue = hevBlockQueueS; - } - } - else { // NO-OP - return unlock( mtxUnblockLock ); - } - - unlock( mtxUnblockLock ); - set_event( hevBlockQueue ); - return result; -} - - ----------------------------------------------------------------------------- - -Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio - n questions -Date: Mon, 26 Feb 2001 22:20:12 -0600 -From: Louis Thomas -To: "'TEREKHOV@de.ibm.com'" -CC: rpj@ise.canberra.edu.au, Thomas Pfaff , - Nanbor Wang - - -Sorry all. Busy week. - -> this insures the fairness -> which POSIX does not (e.g. two subsequent broadcasts - the gate does -insure -> that first wave waiters will start the race for the mutex before waiters -> from the second wave - Linux pthreads process/unblock both waves -> concurrently...) - -I'm not sure how we are any more fair about this than Linux. We certainly -don't guarantee that the threads released by the first broadcast will get -the external mutex before the threads of the second wave. In fact, it is -possible that those threads will never get the external mutex if there is -enough contention for it. - -> e.g. i was thinking about implementation with a pool of -> N semaphores/counters [...] - -I considered that too. The problem is as you mentioned in a). You really -need to assign threads to semaphores once you know how you want to wake them -up, not when they first begin waiting which is the only time you can assign -them. - -> well, i am not quite sure that i've fully understood your scenario, - -Hmm. Well, it think it's an important example, so I'll try again. First, we -have thread A which we KNOW is waiting on a condition. As soon as it becomes -unblocked for any reason, we will know because it will set a flag. Since the -flag is not set, we are 100% confident that thread A is waiting on the -condition. We have another thread, thread B, which has acquired the mutex -and is about to wait on the condition. Thus it is pretty clear that at any -point, either just A is waiting, or A and B are waiting. Now thread C comes -along. C is about to do a broadcast on the condition. A broadcast is -guaranteed to unblock all threads currently waiting on a condition, right? -Again, we said that either just A is waiting, or A and B are both waiting. -So, when C does its broadcast, depending upon whether B has started waiting -or not, thread C will unblock A or unblock A and B. Either way, C must -unblock A, right? - -Now, you said anything that happens is correct so long as a) "a signal is -not lost between unlocking the mutex and waiting on the condition" and b) "a -thread must not steal a signal it sent", correct? Requirement b) is easy to -satisfy: in this scenario, thread C will never wait on the condition, so it -won't steal any signals. Requirement a) is not hard either. The only way we -could fail to meet requirement a) in this scenario is if thread B was -started waiting but didn't wake up because a signal was lost. This will not -happen. - -Now, here is what happens. Assume thread C beats thread B. Thread C looks to -see how many threads are waiting on the condition. Thread C sees just one -thread, thread A, waiting. It does a broadcast waking up just one thread -because just one thread is waiting. Next, before A can become unblocked, -thread B begins waiting. Now there are two threads waiting, but only one -will be unblocked. Suppose B wins. B will become unblocked. A will not -become unblocked, because C only unblocked one thread (sema_post cond, 1). -So at the end, B finishes and A remains blocked. - -We have met both of your requirements, so by your rules, this is an -acceptable outcome. However, I think that the spec says this is an -unacceptable outcome! We know for certain that A was waiting and that C did -a broadcast, but A did not become unblocked! Yet, the spec says that a -broadcast wakes up all waiting threads. This did not happen. Do you agree -that this shows your rules are not strict enough? - -> and what about N2? :) this one does allow almost everything. - -Don't get me started about rule #2. I'll NEVER advocate an algorithm that -uses rule 2 as an excuse to suck! - -> but it is done (decrement)under mutex protection - this is not a subject -> of a race condition. - -You are correct. My mistake. - -> i would remove "_bTimedOut=false".. after all, it was a real timeout.. - -I disagree. A thread that can't successfully retract its waiter status can't -really have timed out. If a thread can't return without executing extra code -to deal with the fact that someone tried to unblock it, I think it is a poor -idea to pretend we -didn't realize someone was trying to signal us. After all, a signal is more -important than a time out. - -> when nSignaled != 0, it is possible to update nWaiters (--) and do not -> touch nGone - -I realize this, but I was thinking that writing it the other ways saves -another if statement. - -> adjust only if nGone != 0 and save one cache memory write - probably much -slower than 'if' - -Hmm. You are probably right. - -> well, in a strange (e.g. timeout test) program you may (theoretically) -> have an overflow of nWaiters/nGone counters (with waiters repeatedly -timing -> out and no signals at all). - -Also true. Not only that, but you also have the possibility that one could -overflow the number of waiters as well! However, considering the limit you -have chosen for nWaitersGone, I suppose it is unlikely that anyone would be -able to get INT_MAX/2 threads waiting on a single condition. :) - -Analysis of 8a: - -It looks correct to me. - -What are IPC semaphores? - -In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { -// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone -because nWaitersGone is never modified without holding mtxUnblockLock. You -are correct that there is a harmless race on nWaitersBlocked, which can -increase and make the condition become true just after we check it. If this -happens, we interpret it as the wait starting after the signal. - -I like your optimization of this. You could improve Alg. 6 as follows: ----------- Algorithm 6b ---------- -signal(bAll) { - _nSig=0 - lock counters - // this is safe because nWaiting can only be decremented by a thread that - // owns counters and nGone can only be changed by a thread that owns -counters. - if (nWaiting>nGone) { - if (0==nSignaled) { - sema_wait gate // close gate if not already closed - } - if (nGone>0) { - nWaiting-=nGone - nGone=0 - } - _nSig=bAll?nWaiting:1 - nSignaled+=_nSig - nWaiting-=_nSig - } - unlock counters - if (0!=_nSig) { - sema_post queue, _nSig - } -} ----------- ---------- ---------- -I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings -depending upon whether the gate is open or closed. - -In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on -semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. - -What have you gained by making the last thread to be signaled do the waits -for all the timed out threads, besides added complexity? It took me a long -time to figure out what your objective was with this, to realize you were -using nWaitersGone to mean two different things, and to verify that you -hadn't introduced any bug by doing this. Even now I'm not 100% sure. - -What has all this playing about with nWaitersGone really gained us besides a -lot of complexity (it is much harder to verify that this solution is -correct), execution overhead (we now have a lot more if statements to -evaluate), and space overhead (more space for the extra code, and another -integer in our data)? We did manage to save a lock/unlock pair in an -uncommon case (when a time out occurs) at the above mentioned expenses in -the common cases. - -As for 8b, c, and d, they look ok though I haven't studied them thoroughly. -What would you use them for? - - Later, - -Louis! :) - ------------------------------------------------------------------------------ - -Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio - n questions -Date: Tue, 27 Feb 2001 15:51:28 +0100 -From: TEREKHOV@de.ibm.com -To: Louis Thomas -CC: rpj@ise.canberra.edu.au, Thomas Pfaff , - Nanbor Wang - -Hi Louis, - ->> that first wave waiters will start the race for the mutex before waiters ->> from the second wave - Linux pthreads process/unblock both waves ->> concurrently...) -> ->I'm not sure how we are any more fair about this than Linux. We certainly ->don't guarantee that the threads released by the first broadcast will get ->the external mutex before the threads of the second wave. In fact, it is ->possible that those threads will never get the external mutex if there is ->enough contention for it. - -correct. but gate is nevertheless more fair than Linux because of the -barrier it establishes between two races (1st and 2nd wave waiters) for -the mutex which under 'normal' circumstances (e.g. all threads of equal -priorities,..) will 'probably' result in fair behaviour with respect to -mutex ownership. - ->> well, i am not quite sure that i've fully understood your scenario, -> ->Hmm. Well, it think it's an important example, so I'll try again. ... - -ok. now i seem to understand this example. well, now it seems to me -that the only meaningful rule is just: - -a) "a signal is not lost between unlocking the mutex and waiting on the -condition" - -and that the rule - -b) "a thread must not steal a signal it sent" - -is not needed at all because a thread which violates b) also violates a). - -i'll try to explain.. - -i think that the most important thing is how POSIX defines waiter's -visibility: - -"if another thread is able to acquire the mutex after the about-to-block -thread -has released it, then a subsequent call to pthread_cond_signal() or -pthread_cond_broadcast() in that thread behaves as if it were issued after -the about-to-block thread has blocked. " - -my understanding is the following: - -1) there is no guarantees whatsoever with respect to whether -signal/broadcast -will actually unblock any 'waiter' if it is done w/o acquiring the mutex -first -(note that a thread may release it before signal/broadcast - it does not -matter). - -2) it is guaranteed that waiters become 'visible' - eligible for unblock as -soon -as signalling thread acquires the mutex (but not before!!) - -so.. - ->So, when C does its broadcast, depending upon whether B has started -waiting ->or not, thread C will unblock A or unblock A and B. Either way, C must ->unblock A, right? - -right. but only if C did acquire the mutex prior to broadcast (it may -release it before broadcast as well). - -implementation will violate waiters visibility rule (signal will become -lost) -if C will not unblock A. - ->Now, here is what happens. Assume thread C beats thread B. Thread C looks -to ->see how many threads are waiting on the condition. Thread C sees just one ->thread, thread A, waiting. It does a broadcast waking up just one thread ->because just one thread is waiting. Next, before A can become unblocked, ->thread B begins waiting. Now there are two threads waiting, but only one ->will be unblocked. Suppose B wins. B will become unblocked. A will not ->become unblocked, because C only unblocked one thread (sema_post cond, 1). ->So at the end, B finishes and A remains blocked. - -thread C did acquire the mutex ("Thread C sees just one thread, thread A, -waiting"). beginning from that moment it is guaranteed that subsequent -broadcast will unblock A. Otherwise we will have a lost signal with respect -to A. I do think that it does not matter whether the signal was physically -(completely) lost or was just stolen by another thread (B) - in both cases -it was simply lost with respect to A. - ->..Do you agree that this shows your rules are not strict enough? - -probably the opposite.. :-) i think that it shows that the only meaningful -rule is - -a) "a signal is not lost between unlocking the mutex and waiting on the -condition" - -with clarification of waiters visibility as defined by POSIX above. - ->> i would remove "_bTimedOut=false".. after all, it was a real timeout.. -> ->I disagree. A thread that can't successfully retract its waiter status -can't ->really have timed out. If a thread can't return without executing extra -code ->to deal with the fact that someone tried to unblock it, I think it is a -poor ->idea to pretend we ->didn't realize someone was trying to signal us. After all, a signal is -more ->important than a time out. - -a) POSIX does allow timed out thread to consume a signal (cancelled is -not). -b) ETIMEDOUT status just says that: "The time specified by abstime to -pthread_cond_timedwait() has passed." -c) it seem to me that hiding timeouts would violate "The -pthread_cond_timedwait() -function is the same as pthread_cond_wait() except that an error is -returned if -the absolute time specified by abstime passes (that is, system time equals -or -exceeds abstime) before the condition cond is signaled or broadcasted" -because -the abs. time did really pass before cond was signaled (waiter was -released via semaphore). however, if it really matters, i could imaging -that we -can save an abs. time of signal/broadcast and compare it with timeout after -unblock to find out whether it was a 'real' timeout or not. absent this -check -i do think that hiding timeouts would result in technical violation of -specification.. but i think that this check is not important and we can -simply -trust timeout error code provided by wait since we are not trying to make -'hard' realtime implementation. - ->What are IPC semaphores? - - -int semctl(int, int, int, ...); -int semget(key_t, int, int); -int semop(int, struct sembuf *, size_t); - -they support adjustment of semaphore counter (semvalue) -in one single call - imaging Win32 ReleaseSemaphore( hsem,-N ) - ->In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { ->// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone ->because nWaitersGone is never modified without holding mtxUnblockLock. You ->are correct that there is a harmless race on nWaitersBlocked, which can ->increase and make the condition become true just after we check it. If -this ->happens, we interpret it as the wait starting after the signal. - -well, the reason why i've asked on comp.programming.threads whether this -race -condition is harmless or not is that in order to be harmless it should not -violate the waiters visibility rule (see above). Fortunately, we increment -the counter under protection of external mutex.. so that any (signalling) -thread which will acquire the mutex next, should see the updated counter -(in signal) according to POSIX memory visibility rules and mutexes -(memory barriers). But i am not so sure how it actually works on -Win32/INTEL -which does not explicitly define any memory visibility rules :( - ->I like your optimization of this. You could improve Alg. 6 as follows: ->---------- Algorithm 6b ---------- ->signal(bAll) { -> _nSig=0 -> lock counters -> // this is safe because nWaiting can only be decremented by a thread -that -> // owns counters and nGone can only be changed by a thread that owns ->counters. -> if (nWaiting>nGone) { -> if (0==nSignaled) { -> sema_wait gate // close gate if not already closed -> } -> if (nGone>0) { -> nWaiting-=nGone -> nGone=0 -> } -> _nSig=bAll?nWaiting:1 -> nSignaled+=_nSig -> nWaiting-=_nSig -> } -> unlock counters -> if (0!=_nSig) { -> sema_post queue, _nSig -> } ->} ->---------- ---------- ---------- ->I guess this wouldn't apply to Alg 8a because nWaitersGone changes -meanings ->depending upon whether the gate is open or closed. - -agree. - ->In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on ->semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. - -you are correct. my mistake. - ->What have you gained by making the last thread to be signaled do the waits ->for all the timed out threads, besides added complexity? It took me a long ->time to figure out what your objective was with this, to realize you were ->using nWaitersGone to mean two different things, and to verify that you ->hadn't introduced any bug by doing this. Even now I'm not 100% sure. -> ->What has all this playing about with nWaitersGone really gained us besides -a ->lot of complexity (it is much harder to verify that this solution is ->correct), execution overhead (we now have a lot more if statements to ->evaluate), and space overhead (more space for the extra code, and another ->integer in our data)? We did manage to save a lock/unlock pair in an ->uncommon case (when a time out occurs) at the above mentioned expenses in ->the common cases. - -well, please consider the following: - -1) with multiple waiters unblocked (but some timed out) the trick with -counter -seem to ensure potentially higher level of concurrency by not delaying -most of unblocked waiters for semaphore cleanup - only the last one -will be delayed but all others would already contend/acquire/release -the external mutex - the critical section protected by mtxUnblockLock is -made smaller (increment + couple of IFs is faster than system/kernel call) -which i think is good in general. however, you are right, this is done -at expense of 'normal' waiters.. - -2) some semaphore APIs (e.g. POSIX IPC sems) do allow to adjust the -semaphore counter in one call => less system/kernel calls.. imagine: - -if ( 1 == nSignalsWasLeft ) { - if ( 0 != nWaitersWasGone ) { - ReleaseSemaphore( semBlockQueue,-nWaitersWasGone ); // better now -than spurious later - } - sem_post( semBlockLock ); // open the gate - } - -3) even on win32 a single thread doing multiple cleanup calls (to wait) -will probably result in faster execution (because of processor caching) -than multiple threads each doing a single call to wait. - ->As for 8b, c, and d, they look ok though I haven't studied them -thoroughly. ->What would you use them for? - -8b) for semaphores which do not allow to unblock multiple waiters -in a single call to post/release (e.g. POSIX realtime semaphores - -) - -8c/8d) for WinCE prior to 3.0 (WinCE 3.0 does have semaphores) - -ok. so, which one is the 'final' algorithm(s) which we should use in -pthreads-win32?? - -regards, -alexander. - ----------------------------------------------------------------------------- - -Louis Thomas on 02/27/2001 05:20:12 AM - -Please respond to Louis Thomas - -To: Alexander Terekhov/Germany/IBM@IBMDE -cc: rpj@ise.canberra.edu.au, Thomas Pfaff , Nanbor Wang - -Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio - n questions - -Sorry all. Busy week. - -> this insures the fairness -> which POSIX does not (e.g. two subsequent broadcasts - the gate does -insure -> that first wave waiters will start the race for the mutex before waiters -> from the second wave - Linux pthreads process/unblock both waves -> concurrently...) - -I'm not sure how we are any more fair about this than Linux. We certainly -don't guarantee that the threads released by the first broadcast will get -the external mutex before the threads of the second wave. In fact, it is -possible that those threads will never get the external mutex if there is -enough contention for it. - -> e.g. i was thinking about implementation with a pool of -> N semaphores/counters [...] - -I considered that too. The problem is as you mentioned in a). You really -need to assign threads to semaphores once you know how you want to wake -them -up, not when they first begin waiting which is the only time you can assign -them. - -> well, i am not quite sure that i've fully understood your scenario, - -Hmm. Well, it think it's an important example, so I'll try again. First, we -have thread A which we KNOW is waiting on a condition. As soon as it -becomes -unblocked for any reason, we will know because it will set a flag. Since -the -flag is not set, we are 100% confident that thread A is waiting on the -condition. We have another thread, thread B, which has acquired the mutex -and is about to wait on the condition. Thus it is pretty clear that at any -point, either just A is waiting, or A and B are waiting. Now thread C comes -along. C is about to do a broadcast on the condition. A broadcast is -guaranteed to unblock all threads currently waiting on a condition, right? -Again, we said that either just A is waiting, or A and B are both waiting. -So, when C does its broadcast, depending upon whether B has started waiting -or not, thread C will unblock A or unblock A and B. Either way, C must -unblock A, right? - -Now, you said anything that happens is correct so long as a) "a signal is -not lost between unlocking the mutex and waiting on the condition" and b) -"a -thread must not steal a signal it sent", correct? Requirement b) is easy to -satisfy: in this scenario, thread C will never wait on the condition, so it -won't steal any signals. Requirement a) is not hard either. The only way -we -could fail to meet requirement a) in this scenario is if thread B was -started waiting but didn't wake up because a signal was lost. This will not -happen. - -Now, here is what happens. Assume thread C beats thread B. Thread C looks -to -see how many threads are waiting on the condition. Thread C sees just one -thread, thread A, waiting. It does a broadcast waking up just one thread -because just one thread is waiting. Next, before A can become unblocked, -thread B begins waiting. Now there are two threads waiting, but only one -will be unblocked. Suppose B wins. B will become unblocked. A will not -become unblocked, because C only unblocked one thread (sema_post cond, 1). -So at the end, B finishes and A remains blocked. - -We have met both of your requirements, so by your rules, this is an -acceptable outcome. However, I think that the spec says this is an -unacceptable outcome! We know for certain that A was waiting and that C did -a broadcast, but A did not become unblocked! Yet, the spec says that a -broadcast wakes up all waiting threads. This did not happen. Do you agree -that this shows your rules are not strict enough? - -> and what about N2? :) this one does allow almost everything. - -Don't get me started about rule #2. I'll NEVER advocate an algorithm that -uses rule 2 as an excuse to suck! - -> but it is done (decrement)under mutex protection - this is not a subject -> of a race condition. - -You are correct. My mistake. - -> i would remove "_bTimedOut=false".. after all, it was a real timeout.. - -I disagree. A thread that can't successfully retract its waiter status -can't -really have timed out. If a thread can't return without executing extra -code -to deal with the fact that someone tried to unblock it, I think it is a -poor -idea to pretend we -didn't realize someone was trying to signal us. After all, a signal is more -important than a time out. - -> when nSignaled != 0, it is possible to update nWaiters (--) and do not -> touch nGone - -I realize this, but I was thinking that writing it the other ways saves -another if statement. - -> adjust only if nGone != 0 and save one cache memory write - probably much -slower than 'if' - -Hmm. You are probably right. - -> well, in a strange (e.g. timeout test) program you may (theoretically) -> have an overflow of nWaiters/nGone counters (with waiters repeatedly -timing -> out and no signals at all). - -Also true. Not only that, but you also have the possibility that one could -overflow the number of waiters as well! However, considering the limit you -have chosen for nWaitersGone, I suppose it is unlikely that anyone would be -able to get INT_MAX/2 threads waiting on a single condition. :) - -Analysis of 8a: - -It looks correct to me. - -What are IPC semaphores? - -In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { -// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone -because nWaitersGone is never modified without holding mtxUnblockLock. You -are correct that there is a harmless race on nWaitersBlocked, which can -increase and make the condition become true just after we check it. If this -happens, we interpret it as the wait starting after the signal. - -I like your optimization of this. You could improve Alg. 6 as follows: ----------- Algorithm 6b ---------- -signal(bAll) { - _nSig=0 - lock counters - // this is safe because nWaiting can only be decremented by a thread that - // owns counters and nGone can only be changed by a thread that owns -counters. - if (nWaiting>nGone) { - if (0==nSignaled) { - sema_wait gate // close gate if not already closed - } - if (nGone>0) { - nWaiting-=nGone - nGone=0 - } - _nSig=bAll?nWaiting:1 - nSignaled+=_nSig - nWaiting-=_nSig - } - unlock counters - if (0!=_nSig) { - sema_post queue, _nSig - } -} ----------- ---------- ---------- -I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings -depending upon whether the gate is open or closed. - -In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on -semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. - -What have you gained by making the last thread to be signaled do the waits -for all the timed out threads, besides added complexity? It took me a long -time to figure out what your objective was with this, to realize you were -using nWaitersGone to mean two different things, and to verify that you -hadn't introduced any bug by doing this. Even now I'm not 100% sure. - -What has all this playing about with nWaitersGone really gained us besides -a -lot of complexity (it is much harder to verify that this solution is -correct), execution overhead (we now have a lot more if statements to -evaluate), and space overhead (more space for the extra code, and another -integer in our data)? We did manage to save a lock/unlock pair in an -uncommon case (when a time out occurs) at the above mentioned expenses in -the common cases. - -As for 8b, c, and d, they look ok though I haven't studied them thoroughly. -What would you use them for? - - Later, - -Louis! :) - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README.NONPORTABLE b/bridge/third_party/quickjs/compat/win32/pthreads/README.NONPORTABLE deleted file mode 100644 index 9bdc445c7a..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README.NONPORTABLE +++ /dev/null @@ -1,783 +0,0 @@ -This file documents non-portable functions and other issues. - -Non-portable functions included in pthreads-win32 -------------------------------------------------- - -BOOL -pthread_win32_test_features_np(int mask) - - This routine allows an application to check which - run-time auto-detected features are available within - the library. - - The possible features are: - - PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE - Return TRUE if the native version of - InterlockedCompareExchange() is being used. - This feature is not meaningful in recent - library versions as MSVC builds only support - system implemented ICE. Note that all Mingw - builds use inlined asm versions of all the - Interlocked routines. - PTW32_ALERTABLE_ASYNC_CANCEL - Return TRUE is the QueueUserAPCEx package - QUSEREX.DLL is available and the AlertDrv.sys - driver is loaded into Windows, providing - alertable (pre-emptive) asyncronous threads - cancelation. If this feature returns FALSE - then the default async cancel scheme is in - use, which cannot cancel blocked threads. - - Features may be Or'ed into the mask parameter, in which case - the routine returns TRUE if any of the Or'ed features would - return TRUE. At this stage it doesn't make sense to Or features - but it may some day. - - -void * -pthread_timechange_handler_np(void *) - - To improve tolerance against operator or time service - initiated system clock changes. - - This routine can be called by an application when it - receives a WM_TIMECHANGE message from the system. At - present it broadcasts all condition variables so that - waiting threads can wake up and re-evaluate their - conditions and restart their timed waits if required. - - It has the same return type and argument type as a - thread routine so that it may be called directly - through pthread_create(), i.e. as a separate thread. - - Parameters - - Although a parameter must be supplied, it is ignored. - The value NULL can be used. - - Return values - - It can return an error EAGAIN to indicate that not - all condition variables were broadcast for some reason. - Otherwise, 0 is returned. - - If run as a thread, the return value is returned - through pthread_join(). - - The return value should be cast to an integer. - - -HANDLE -pthread_getw32threadhandle_np(pthread_t thread); - - Returns the win32 thread handle that the POSIX - thread "thread" is running as. - - Applications can use the win32 handle to set - win32 specific attributes of the thread. - -DWORD -pthread_getw32threadid_np (pthread_t thread) - - Returns the Windows native thread ID that the POSIX - thread "thread" is running as. - - Only valid when the library is built where - ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) - and otherwise returns 0. - - -int -pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr, int kind) - -int -pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr, int *kind) - - These two routines are included for Linux compatibility - and are direct equivalents to the standard routines - pthread_mutexattr_settype - pthread_mutexattr_gettype - - pthread_mutexattr_setkind_np accepts the following - mutex kinds: - PTHREAD_MUTEX_FAST_NP - PTHREAD_MUTEX_ERRORCHECK_NP - PTHREAD_MUTEX_RECURSIVE_NP - - These are really just equivalent to (respectively): - PTHREAD_MUTEX_NORMAL - PTHREAD_MUTEX_ERRORCHECK - PTHREAD_MUTEX_RECURSIVE - -int -pthread_delay_np (const struct timespec *interval); - - This routine causes a thread to delay execution for a specific period of time. - This period ends at the current time plus the specified interval. The routine - will not return before the end of the period is reached, but may return an - arbitrary amount of time after the period has gone by. This can be due to - system load, thread priorities, and system timer granularity. - - Specifying an interval of zero (0) seconds and zero (0) nanoseconds is - allowed and can be used to force the thread to give up the processor or to - deliver a pending cancelation request. - - This routine is a cancelation point. - - The timespec structure contains the following two fields: - - tv_sec is an integer number of seconds. - tv_nsec is an integer number of nanoseconds. - - Return Values - - If an error condition occurs, this routine returns an integer value - indicating the type of error. Possible return values are as follows: - - 0 Successful completion. - [EINVAL] The value specified by interval is invalid. - -int -pthread_num_processors_np (void) - - This routine (found on HPUX systems) returns the number of processors - in the system. This implementation actually returns the number of - processors available to the process, which can be a lower number - than the system's number, depending on the process's affinity mask. - -BOOL -pthread_win32_process_attach_np (void); - -BOOL -pthread_win32_process_detach_np (void); - -BOOL -pthread_win32_thread_attach_np (void); - -BOOL -pthread_win32_thread_detach_np (void); - - These functions contain the code normally run via dllMain - when the library is used as a dll but which need to be - called explicitly by an application when the library - is statically linked. As of version 2.9.0 of the library, static - builds using either MSC or GCC will call pthread_win32_process_* - automatically at application startup and exit respectively. - - Otherwise, you will need to call pthread_win32_process_attach_np() - before you can call any pthread routines when statically linking. - You should call pthread_win32_process_detach_np() before - exiting your application to clean up. - - pthread_win32_thread_attach_np() is currently a no-op, but - pthread_win32_thread_detach_np() is needed to clean up - the implicit pthread handle that is allocated to a Win32 thread if - it calls any pthreads routines. Call this routine when the - Win32 thread exits. - - Threads created through pthread_create() do not need to call - pthread_win32_thread_detach_np(). - - These functions invariably return TRUE except for - pthread_win32_process_attach_np() which will return FALSE - if pthreads-win32 initialisation fails. - -int -pthreadCancelableWait (HANDLE waitHandle); - -int -pthreadCancelableTimedWait (HANDLE waitHandle, DWORD timeout); - - These two functions provide hooks into the pthread_cancel - mechanism that will allow you to wait on a Windows handle - and make it a cancellation point. Both functions block - until either the given w32 handle is signaled, or - pthread_cancel has been called. It is implemented using - WaitForMultipleObjects on 'waitHandle' and a manually - reset w32 event used to implement pthread_cancel. - - -Non-portable issues -------------------- - -Thread priority - - POSIX defines a single contiguous range of numbers that determine a - thread's priority. Win32 defines priority classes and priority - levels relative to these classes. Classes are simply priority base - levels that the defined priority levels are relative to such that, - changing a process's priority class will change the priority of all - of it's threads, while the threads retain the same relativity to each - other. - - A Win32 system defines a single contiguous monotonic range of values - that define system priority levels, just like POSIX. However, Win32 - restricts individual threads to a subset of this range on a - per-process basis. - - The following table shows the base priority levels for combinations - of priority class and priority value in Win32. - - Process Priority Class Thread Priority Level - ----------------------------------------------------------------- - 1 IDLE_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 1 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 1 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 1 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 1 HIGH_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 2 IDLE_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 3 IDLE_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 4 IDLE_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 4 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 5 IDLE_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 5 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 5 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 6 IDLE_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 6 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 6 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 7 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 7 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 7 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 8 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 8 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 8 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 8 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 9 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 9 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 9 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 10 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 10 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 11 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 11 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 11 HIGH_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 12 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 12 HIGH_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 13 HIGH_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 14 HIGH_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - 15 IDLE_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - 15 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - 15 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - 15 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - 16 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_IDLE - 17 REALTIME_PRIORITY_CLASS -7 - 18 REALTIME_PRIORITY_CLASS -6 - 19 REALTIME_PRIORITY_CLASS -5 - 20 REALTIME_PRIORITY_CLASS -4 - 21 REALTIME_PRIORITY_CLASS -3 - 22 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_LOWEST - 23 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL - 24 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_NORMAL - 25 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL - 26 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST - 27 REALTIME_PRIORITY_CLASS 3 - 28 REALTIME_PRIORITY_CLASS 4 - 29 REALTIME_PRIORITY_CLASS 5 - 30 REALTIME_PRIORITY_CLASS 6 - 31 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL - - Windows NT: Values -7, -6, -5, -4, -3, 3, 4, 5, and 6 are not supported. - - - As you can see, the real priority levels available to any individual - Win32 thread are non-contiguous. - - An application using pthreads-win32 should not make assumptions about - the numbers used to represent thread priority levels, except that they - are monotonic between the values returned by sched_get_priority_min() - and sched_get_priority_max(). E.g. Windows 95, 98, NT, 2000, XP make - available a non-contiguous range of numbers between -15 and 15, while - at least one version of WinCE (3.0) defines the minimum priority - (THREAD_PRIORITY_LOWEST) as 5, and the maximum priority - (THREAD_PRIORITY_HIGHEST) as 1. - - Internally, pthreads-win32 maps any priority levels between - THREAD_PRIORITY_IDLE and THREAD_PRIORITY_LOWEST to THREAD_PRIORITY_LOWEST, - or between THREAD_PRIORITY_TIME_CRITICAL and THREAD_PRIORITY_HIGHEST to - THREAD_PRIORITY_HIGHEST. Currently, this also applies to - REALTIME_PRIORITY_CLASSi even if levels -7, -6, -5, -4, -3, 3, 4, 5, and 6 - are supported. - - If it wishes, a Win32 application using pthreads-win32 can use the Win32 - defined priority macros THREAD_PRIORITY_IDLE through - THREAD_PRIORITY_TIME_CRITICAL. - - -The opacity of the pthread_t datatype -------------------------------------- -and possible solutions for portable null/compare/hash, etc ----------------------------------------------------------- - -Because pthread_t is an opague datatype an implementation is permitted to define -pthread_t in any way it wishes. That includes defining some bits, if it is -scalar, or members, if it is an aggregate, to store information that may be -extra to the unique identifying value of the ID. As a result, pthread_t values -may not be directly comparable. - -If you want your code to be portable you must adhere to the following contraints: - -1) Don't assume it is a scalar data type, e.g. an integer or pointer value. There -are several other implementations where pthread_t is also a struct. See our FAQ -Question 11 for our reasons for defining pthread_t as a struct. - -2) You must not compare them using relational or equality operators. You must use -the API function pthread_equal() to test for equality. - -3) Never attempt to reference individual members. - - -The problem - -Certain applications would like to be able to access only the 'pure' pthread_t -id values, primarily to use as keys into data structures to manage threads or -thread-related data, but this is not possible in a maximally portable and -standards compliant way for current POSIX threads implementations. - -For implementations that define pthread_t as a scalar, programmers often employ -direct relational and equality operators on pthread_t. This code will break when -ported to an implementation that defines pthread_t as an aggregate type. - -For implementations that define pthread_t as an aggregate, e.g. a struct, -programmers can use memcmp etc., but then face the prospect that the struct may -include alignment padding bytes or bits as well as extra implementation-specific -members that are not part of the unique identifying value. - -[While this is not currently the case for pthreads-win32, opacity also -means that an implementation is free to change the definition, which should -generally only require that applications be recompiled and relinked, not -rewritten.] - - -Doesn't the compiler take care of padding? - -The C89 and later standards only effectively guarrantee element-by-element -equivalence following an assignment or pass by value of a struct or union, -therefore undefined areas of any two otherwise equivalent pthread_t instances -can still compare differently, e.g. attempting to compare two such pthread_t -variables byte-by-byte, e.g. memcmp(&t1, &t2, sizeof(pthread_t) may give an -incorrect result. In practice I'm reasonably confident that compilers routinely -also copy the padding bytes, mainly because assignment of unions would be far -too complicated otherwise. But it just isn't guarranteed by the standard. - -Illustration: - -We have two thread IDs t1 and t2 - -pthread_t t1, t2; - -In an application we create the threads and intend to store the thread IDs in an -ordered data structure (linked list, tree, etc) so we need to be able to compare -them in order to insert them initially and also to traverse. - -Suppose pthread_t contains undefined padding bits and our compiler copies our -pthread_t [struct] element-by-element, then for the assignment: - -pthread_t temp = t1; - -temp and t1 will be equivalent and correct but a byte-for-byte comparison such as -memcmp(&temp, &t1, sizeof(pthread_t)) == 0 may not return true as we expect because -the undefined bits may not have the same values in the two variable instances. - -Similarly if passing by value under the same conditions. - -If, on the other hand, the undefined bits are at least constant through every -assignment and pass-by-value then the byte-for-byte comparison -memcmp(&temp, &t1, sizeof(pthread_t)) == 0 will always return the expected result. -How can we force the behaviour we need? - - -Solutions - -Adding new functions to the standard API or as non-portable extentions is -the only reliable and portable way to provide the necessary operations. -Remember also that POSIX is not tied to the C language. The most common -functions that have been suggested are: - -pthread_null() -pthread_compare() -pthread_hash() - -A single more general purpose function could also be defined as a -basis for at least the last two of the above functions. - -First we need to list the freedoms and constraints with restpect -to pthread_t so that we can be sure our solution is compatible with the -standard. - -What is known or may be deduced from the standard: -1) pthread_t must be able to be passed by value, so it must be a single object. -2) from (1) it must be copyable so cannot embed thread-state information, locks -or other volatile objects required to manage the thread it associates with. -3) pthread_t may carry additional information, e.g. for debugging or to manage -itself. -4) there is an implicit requirement that the size of pthread_t is determinable -at compile-time and size-invariant, because it must be able to copy the object -(i.e. through assignment and pass-by-value). Such copies must be genuine -duplicates, not merely a copy of a pointer to a common instance such as -would be the case if pthread_t were defined as an array. - - -Suppose we define the following function: - -/* This function shall return it's argument */ -pthread_t* pthread_normalize(pthread_t* thread); - -For scalar or aggregate pthread_t types this function would simply zero any bits -within the pthread_t that don't uniquely identify the thread, including padding, -such that client code can return consistent results from operations done on the -result. If the additional bits are a pointer to an associate structure then -this function would ensure that the memory used to store that associate -structure does not leak. After normalization the following compare would be -valid and repeatable: - -memcmp(pthread_normalize(&t1),pthread_normalize(&t2),sizeof(pthread_t)) - -Note 1: such comparisons are intended merely to order and sort pthread_t values -and allow them to index various data structures. They are not intended to reveal -anything about the relationships between threads, like startup order. - -Note 2: the normalized pthread_t is also a valid pthread_t that uniquely -identifies the same thread. - -Advantages: -1) In most existing implementations this function would reduce to a no-op that -emits no additional instructions, i.e after in-lining or optimisation, or if -defined as a macro: -#define pthread_normalise(tptr) (tptr) - -2) This single function allows an application to portably derive -application-level versions of any of the other required functions. - -3) It is a generic function that could enable unanticipated uses. - -Disadvantages: -1) Less efficient than dedicated compare or hash functions for implementations -that include significant extra non-id elements in pthread_t. - -2) Still need to be concerned about padding if copying normalized pthread_t. -See the later section on defining pthread_t to neutralise padding issues. - -Generally a pthread_t may need to be normalized every time it is used, -which could have a significant impact. However, this is a design decision -for the implementor in a competitive environment. An implementation is free -to define a pthread_t in a way that minimises or eliminates padding or -renders this function a no-op. - -Hazards: -1) Pass-by-reference directly modifies 'thread' so the application must -synchronise access or ensure that the pointer refers to a copy. The alternative -of pass-by-value/return-by-value was considered but then this requires two copy -operations, disadvantaging implementations where this function is not a no-op -in terms of speed of execution. This function is intended to be used in high -frequency situations and needs to be efficient, or at least not unnecessarily -inefficient. The alternative also sits awkwardly with functions like memcmp. - -2) [Non-compliant] code that uses relational and equality operators on -arithmetic or pointer style pthread_t types would need to be rewritten, but it -should be rewritten anyway. - - -C implementation of null/compare/hash functions using pthread_normalize(): - -/* In pthread.h */ -pthread_t* pthread_normalize(pthread_t* thread); - -/* In user code */ -/* User-level bitclear function - clear bits in loc corresponding to mask */ -void* bitclear (void* loc, void* mask, size_t count); - -typedef unsigned int hash_t; - -/* User-level hash function */ -hash_t hash(void* ptr, size_t count); - -/* - * User-level pthr_null function - modifies the origin thread handle. - * The concept of a null pthread_t is highly implementation dependent - * and this design may be far from the mark. For example, in an - * implementation "null" may mean setting a special value inside one - * element of pthread_t to mean "INVALID". However, if that value was zero and - * formed part of the id component then we may get away with this design. - */ -pthread_t* pthr_null(pthread_t* tp) -{ - /* - * This should have the same effect as memset(tp, 0, sizeof(pthread_t)) - * We're just showing that we can do it. - */ - void* p = (void*) pthread_normalize(tp); - return (pthread_t*) bitclear(p, p, sizeof(pthread_t)); -} - -/* - * Safe user-level pthr_compare function - modifies temporary thread handle copies - */ -int pthr_compare_safe(pthread_t thread1, pthread_t thread2) -{ - return memcmp(pthread_normalize(&thread1), pthread_normalize(&thread2), sizeof(pthread_t)); -} - -/* - * Fast user-level pthr_compare function - modifies origin thread handles - */ -int pthr_compare_fast(pthread_t* thread1, pthread_t* thread2) -{ - return memcmp(pthread_normalize(&thread1), pthread_normalize(&thread2), sizeof(pthread_t)); -} - -/* - * Safe user-level pthr_hash function - modifies temporary thread handle copy - */ -hash_t pthr_hash_safe(pthread_t thread) -{ - return hash((void *) pthread_normalize(&thread), sizeof(pthread_t)); -} - -/* - * Fast user-level pthr_hash function - modifies origin thread handle - */ -hash_t pthr_hash_fast(pthread_t thread) -{ - return hash((void *) pthread_normalize(&thread), sizeof(pthread_t)); -} - -/* User-level bitclear function - modifies the origin array */ -void* bitclear(void* loc, void* mask, size_t count) -{ - int i; - for (i=0; i < count; i++) { - (unsigned char) *loc++ &= ~((unsigned char) *mask++); - } -} - -/* Donald Knuth hash */ -hash_t hash(void* str, size_t count) -{ - hash_t hash = (hash_t) count; - unsigned int i = 0; - - for(i = 0; i < len; str++, i++) - { - hash = ((hash << 5) ^ (hash >> 27)) ^ (*str); - } - return hash; -} - -/* Example of advantage point (3) - split a thread handle into its id and non-id values */ -pthread_t id = thread, non-id = thread; -bitclear((void*) &non-id, (void*) pthread_normalize(&id), sizeof(pthread_t)); - - -A pthread_t type change proposal to neutralise the effects of padding - -Even if pthread_nornalize() is available, padding is still a problem because -the standard only garrantees element-by-element equivalence through -copy operations (assignment and pass-by-value). So padding bit values can -still change randomly after calls to pthread_normalize(). - -[I suspect that most compilers take the easy path and always byte-copy anyway, -partly because it becomes too complex to do (e.g. unions that contain sub-aggregates) -but also because programmers can easily design their aggregates to minimise and -often eliminate padding]. - -How can we eliminate the problem of padding bytes in structs? Could -defining pthread_t as a union rather than a struct provide a solution? - -In fact, the Linux pthread.h defines most of it's pthread_*_t objects (but not -pthread_t itself) as unions, possibly for this and/or other reasons. We'll -borrow some element naming from there but the ideas themselves are well known -- the __align element used to force alignment of the union comes from K&R's -storage allocator example. - -/* Essentially our current pthread_t renamed */ -typedef struct { - struct thread_state_t * __p; - long __x; /* sequence counter */ -} thread_id_t; - -Ensuring that the last element in the above struct is a long ensures that the -overall struct size is a multiple of sizeof(long), so there should be no trailing -padding in this struct or the union we define below. -(Later we'll see that we can handle internal but not trailing padding.) - -/* New pthread_t */ -typedef union { - char __size[sizeof(thread_id_t)]; /* array as the first element */ - thread_id_t __tid; - long __align; /* Ensure that the union starts on long boundary */ -} pthread_t; - -This guarrantees that, during an assignment or pass-by-value, the compiler copies -every byte in our thread_id_t because the compiler guarrantees that the __size -array, which we have ensured is the equal-largest element in the union, retains -equivalence. - -This means that pthread_t values stored, assigned and passed by value will at least -carry the value of any undefined padding bytes along and therefore ensure that -those values remain consistent. Our comparisons will return consistent results and -our hashes of [zero initialised] pthread_t values will also return consistent -results. - -We have also removed the need for a pthread_null() function; we can initialise -at declaration time or easily create our own const pthread_t to use in assignments -later: - -const pthread_t null_tid = {0}; /* braces are required */ - -pthread_t t; -... -t = null_tid; - - -Note that we don't have to explicitly make use of the __size array at all. It's -there just to force the compiler behaviour we want. - - -Partial solutions without a pthread_normalize function - - -An application-level pthread_null and pthread_compare proposal -(and pthread_hash proposal by extention) - -In order to deal with the problem of scalar/aggregate pthread_t type disparity in -portable code I suggest using an old-fashioned union, e.g.: - -Contraints: -- there is no padding, or padding values are preserved through assignment and - pass-by-value (see above); -- there are no extra non-id values in the pthread_t. - - -Example 1: A null initialiser for pthread_t variables... - -typedef union { - unsigned char b[sizeof(pthread_t)]; - pthread_t t; -} init_t; - -const init_t initial = {0}; - -pthread_t tid = initial.t; /* init tid to all zeroes */ - - -Example 2: A comparison function for pthread_t values - -typedef union { - unsigned char b[sizeof(pthread_t)]; - pthread_t t; -} pthcmp_t; - -int pthcmp(pthread_t left, pthread_t right) -{ - /* - * Compare two pthread handles in a way that imposes a repeatable but arbitrary - * ordering on them. - * I.e. given the same set of pthread_t handles the ordering should be the same - * each time but the order has no particular meaning other than that. E.g. - * the ordering does not imply the thread start sequence, or any other - * relationship between threads. - * - * Return values are: - * 1 : left is greater than right - * 0 : left is equal to right - * -1 : left is less than right - */ - int i; - pthcmp_t L, R; - L.t = left; - R.t = right; - for (i = 0; i < sizeof(pthread_t); i++) - { - if (L.b[i] > R.b[i]) - return 1; - else if (L.b[i] < R.b[i]) - return -1; - } - return 0; -} - -It has been pointed out that the C99 standard allows for the possibility that -integer types also may include padding bits, which could invalidate the above -method. This addition to C99 was specifically included after it was pointed -out that there was one, presumably not particularly well known, architecture -that included a padding bit in it's 32 bit integer type. See section 6.2.6.2 -of both the standard and the rationale, specifically the paragraph starting at -line 16 on page 43 of the rationale. - - -An aside - -Certain compilers, e.g. gcc and one of the IBM compilers, include a feature -extention: provided the union contains a member of the same type as the -object then the object may be cast to the union itself. - -We could use this feature to speed up the pthrcmp() function from example 2 -above by casting rather than assigning the pthread_t arguments to the union, e.g.: - -int pthcmp(pthread_t left, pthread_t right) -{ - /* - * Compare two pthread handles in a way that imposes a repeatable but arbitrary - * ordering on them. - * I.e. given the same set of pthread_t handles the ordering should be the same - * each time but the order has no particular meaning other than that. E.g. - * the ordering does not imply the thread start sequence, or any other - * relationship between threads. - * - * Return values are: - * 1 : left is greater than right - * 0 : left is equal to right - * -1 : left is less than right - */ - int i; - for (i = 0; i < sizeof(pthread_t); i++) - { - if (((pthcmp_t)left).b[i] > ((pthcmp_t)right).b[i]) - return 1; - else if (((pthcmp_t)left).b[i] < ((pthcmp_t)right).b[i]) - return -1; - } - return 0; -} - - -Result thus far - -We can't remove undefined bits if they are there in pthread_t already, but we have -attempted to render them inert for comparison and hashing functions by making them -consistent through assignment, copy and pass-by-value. - -Note: Hashing pthread_t values requires that all pthread_t variables be initialised -to the same value (usually all zeros) before being assigned a proper thread ID, i.e. -to ensure that any padding bits are zero, or at least the same value for all -pthread_t. Since all pthread_t values are generated by the library in the first -instance this need not be an application-level operation. - - -Conclusion - -I've attempted to resolve the multiple issues of type opacity and the possible -presence of undefined bits and bytes in pthread_t values, which prevent -applications from comparing or hashing pthread handles. - -Two complimentary partial solutions have been proposed, one an application-level -scheme to handle both scalar and aggregate pthread_t types equally, plus a -definition of pthread_t itself that neutralises padding bits and bytes by -coercing semantics out of the compiler to eliminate variations in the values of -padding bits. - -I have not provided any solution to the problem of handling extra values embedded -in pthread_t, e.g. debugging or trap information that an implementation is entitled -to include. Therefore none of this replaces the portability and flexibility of API -functions but what functions are needed? The threads standard is unlikely to -include that can be implemented by a combination of existing features and more -generic functions (several references in the threads rationale suggest this. -Therefore I propose that the following function could replace the several functions -that have been suggested in conversations: - -pthread_t * pthread_normalize(pthread_t * handle); - -For most existing pthreads implementations this function, or macro, would reduce to -a no-op with zero call overhead. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README.Watcom b/bridge/third_party/quickjs/compat/win32/pthreads/README.Watcom deleted file mode 100644 index 2974928a38..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README.Watcom +++ /dev/null @@ -1,62 +0,0 @@ -Watcom compiler notes -===================== - -Status ------- -Not yet usable. Although the library builds under Watcom it -substantially fails the test suite. - -There is a working Wmakefile for wmake for the library build. - -invoke as any of: -wmake -f Wmakefile clean WC -wmake -f Wmakefile clean WC-inlined -wmake -f Wmakefile clean WCE -wmake -f Wmakefile clean WCE-inlined - -These build pthreadWC.dll and pthreadWCE.dll. - -There is a working Wmakefile for wmake for the test suite. - -invoke as any of: -wmake -f Wmakefile clean WC -wmake -f Wmakefile clean WCX -wmake -f Wmakefile clean WCE -wmake -f Wmakefile clean WC-bench -wmake -f Wmakefile clean WCX-bench -wmake -f Wmakefile clean WCE-bench - - -Current known problems ----------------------- - -Library build: -The Watcom compiler uses a different default call convention to MS C or GNU C and so -applications are not compatible with pthreadVC.dll etc using pre 2003-10-14 versions -of pthread.h, sched.h, or semaphore.h. The cdecl attribute can be used on exposed -function prototypes to force compatibility with MS C built DLLs. - -However, there appear to be other incompatibilities. Errno.h, for example, defines -different values for the standard C and POSIX errors to those defined by the MS C -errno.h. It may be that references to Watcom's threads compatible 'errno' do set -and return translated numbers consistently, but I have not verified this. - -Watcom defines errno as a dereferenced pointer returned by the function -_get_errno_ptr(). This is similar to both the MS and GNU C environments for -multithreaded use. However, the Watcom version appears to have a number of problems: - -- different threads return the same pointer value. Compare with the MS and GNU C -versions which correctly return different values (since each thread must maintain -a thread specific errno value). - -- an errno value set within the DLL appears as zero in the application even though -both share the same thread. - -Therefore applications built using the Watcom compiler may need to use -a Watcom built version of the library (pthreadWC.dll). If this is the case, then -the cdecl function attribute should not be required. - -Application builds: -The test suite fails with the Watcom compiler. - -Test semaphore1.c fails for pthreadWC.dll because errno returns 0 instead of EAGAIN. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/README.WinCE b/bridge/third_party/quickjs/compat/win32/pthreads/README.WinCE deleted file mode 100644 index a2cd8c2133..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/README.WinCE +++ /dev/null @@ -1,6 +0,0 @@ -WinCE port ----------- -(See the file WinCE-PORT for a detailed explanation.) - -Make sure you define "WINCE" amongst your compiler flags (eg. -DWINCE). -The config.h file will define all the necessary defines for you. diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/WinCE-PORT b/bridge/third_party/quickjs/compat/win32/pthreads/WinCE-PORT deleted file mode 100644 index 7bcfdea6cc..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/WinCE-PORT +++ /dev/null @@ -1,222 +0,0 @@ -NOTE: The comments in this file relate to the original WinCE port -done by Tristan Savatier. The semaphore routines have been -completely rewritten since (2005-04-25), having been progressively -broken more and more by changes to the library. All of the semaphore -routines implemented for W9x/WNT/2000 and up should now also work for -WinCE. Also, pthread_mutex_timedlock should now work. - -Additional WinCE updates have been applied since this as well. Check the -ChangeLog file and search for WINCE for example. (2007-01-07) - -[RPJ] - ----- - -Some interesting news: - -I have been able to port pthread-win32 to Windows-CE, -which uses a subset of the WIN32 API. - -Since we intend to keep using pthread-win32 for our -Commercial WinCE developments, I would be very interested -if WinCE support could be added to the main source tree -of pthread-win32. Also, I would like to be credited -for this port :-) - -Now, here is the story... - -The port was performed and tested on a Casio "Cassiopeia" -PalmSize PC, which runs a MIP processor. The OS in the -Casio is WinCE version 2.11, but I used VC++ 6.0 with -the WinCE SDK for version 2.01. - -I used pthread-win32 to port a heavily multithreaded -commercial application (real-time MPEG video player) -from Linux to WinCE. I consider the changes that -I have done to be quite well tested. - -Overall the modifications that we had to do are minor. - -The WinCE port were based on pthread-win32-snap-1999-05-30, -but I am certain that they can be integrated very easiely -to more recent versions of the source. - -I have attached the modified source code: -pthread-win32-snap-1999-05-30-WinCE. - -All the changes do not affect the code compiled on non-WinCE -environment, provided that the macros used for WinCE compilation -are not used, of course! - -Overall description of the WinCE port: -------------------------------------- - -Most of the changes had to be made in areas where -pthread-win32 was relying on some standard-C librairies -(e.g. _ftime, calloc, errno), which are not available -on WinCE. We have changed the code to use native Win32 -API instead (or in some cases we made wrappers). - -The Win32 Semaphores are not available, -so we had to re-implement Semaphores using mutexes -and events. - -Limitations / known problems of the WinCE port: ----------------------------------------------- - -Not all the semaphore routines have been ported -(semaphores are defined by Posix but are not part -pf pthread). I have just done enough to make -pthread routines (that rely internally on semaphores) -work, like signal conditions. - -I noticed that the Win32 threads work slightly -differently on WinCE. This may have some impact -on some tricky parts of pthread-win32, but I have -not really investigated. For example, on WinCE, -the process is killed if the main thread falls off -the bottom (or calls pthread_exit), regardless -of the existence of any other detached thread. -Microsoft manual indicates that this behavior is -deffirent from that of Windows Threads for other -Win32 platforms. - - -Detailed descriptions of the changes and rationals: - ------------------------------------- -- use a new macro NEED_ERRNO. - -If defined, the code in errno.c that defines a reentrant errno -is compiled, regardless of _MT and _REENTRANT. - -Rational: On WinCE, there is no support for , or -any other standard C library, i.e. even if _MT or _REENTRANT -is defined, errno is not provided by any library. NEED_ERRNO -must be set to compile for WinCE. - ------------------------------------- -- In implement.h, change #include to #include "semaphore.h". - -Rational: semaphore.h is provided in pthread-win32 and should not -be searched in the systems standard include. would not compile. -This change does not seem to create problems on "classic" win32 -(e.g. win95). - ------------------------------------- -- use a new macro NEED_CALLOC. - -If defined, some code in misc.c will provide a replacement -for calloc, which is not available on Win32. - - ------------------------------------- -- use a new macro NEED_CREATETHREAD. - -If defined, implement.h defines the macro _beginthreadex -and _endthreadex. - -Rational: On WinCE, the wrappers _beginthreadex and _endthreadex -do not exist. The native Win32 routines must be used. - ------------------------------------- -- in misc.c: - -#ifdef NEED_DUPLICATEHANDLE - /* DuplicateHandle does not exist on WinCE */ - self->threadH = GetCurrentThread(); -#else - if( !DuplicateHandle( - GetCurrentProcess(), - GetCurrentThread(), - GetCurrentProcess(), - &self->threadH, - 0, - FALSE, - DUPLICATE_SAME_ACCESS ) ) - { - free( self ); - return (NULL); - } -#endif - -Rational: On WinCE, DuplicateHandle does not exist. I could not understand -why DuplicateHandle must be used. It seems to me that getting the current -thread handle with GetCurrentThread() is sufficient, and it seems to work -perfectly fine, so maybe DuplicateHandle was just plain useless to begin with ? - ------------------------------------- -- In private.c, added some code at the beginning of ptw32_processInitialize -to detect the case of multiple calls to ptw32_processInitialize. - -Rational: In order to debug pthread-win32, it is easier to compile -it as a regular library (it is not possible to debug DLL's on winCE). -In that case, the application must call ptw32_rocessInitialize() -explicitely, to initialize pthread-win32. It is safer in this circumstance -to handle the case where ptw32_processInitialize() is called on -an already initialized library: - -int -ptw32_processInitialize (void) -{ - if (ptw32_processInitialized) { - /* - * ignore if already initialized. this is useful for - * programs that uses a non-dll pthread - * library. such programs must call ptw32_processInitialize() explicitely, - * since this initialization routine is automatically called only when - * the dll is loaded. - */ - return TRUE; - } - ptw32_processInitialized = TRUE; - [...] -} - ------------------------------------- -- in private.c, if macro NEED_FTIME is defined, add routines to -convert timespec_to_filetime and filetime_to_timespec, and modified -code that was using _ftime() to use Win32 API instead. - -Rational: _ftime is not available on WinCE. It is necessary to use -the native Win32 time API instead. - -Note: the routine timespec_to_filetime is provided as a convenience and a mean -to test that filetime_to_timespec works, but it is not used by the library. - ------------------------------------- -- in semaphore.c, if macro NEED_SEM is defined, add code for the routines -_increase_semaphore and _decrease_semaphore, and modify significantly -the implementation of the semaphores so that it does not use CreateSemaphore. - -Rational: CreateSemaphore is not available on WinCE. I had to re-implement -semaphores using mutexes and Events. - -Note: Only the semaphore routines that are used by pthread are implemented -(i.e. signal conditions rely on a subset of the semaphores routines, and -this subset works). Some other semaphore routines (e.g. sem_trywait) are -not yet supported on my WinCE port (and since I don't need them, I am not -planning to do anything about them). - ------------------------------------- -- in tsd.c, changed the code that defines TLS_OUT_OF_INDEXES - -/* TLS_OUT_OF_INDEXES not defined on WinCE */ -#ifndef TLS_OUT_OF_INDEXES -#define TLS_OUT_OF_INDEXES 0xffffffff -#endif - -Rational: TLS_OUT_OF_INDEXES is not defined in any standard include file -on WinCE. - ------------------------------------- -- added file need_errno.h - -Rational: On WinCE, there is no errno.h file. need_errno.h is just a -copy of windows version of errno.h, with minor modifications due to the fact -that some of the error codes are defined by the WinCE socket library. -In pthread.h, if NEED_ERRNO is defined, the file need_errno.h is -included (instead of ). - - --- eof diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadGC2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadGC2.dll deleted file mode 100644 index 841d4a2169..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadGC2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadVC2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadVC2.dll deleted file mode 100644 index 165b4d26ec..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x64/pthreadVC2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGC2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGC2.dll deleted file mode 100644 index 67b9289dfd..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGC2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGCE2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGCE2.dll deleted file mode 100644 index 9e18ea24b8..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadGCE2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVC2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVC2.dll deleted file mode 100644 index fcb5d9dcc1..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVC2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVCE2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVCE2.dll deleted file mode 100644 index 9d148cc0da..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVCE2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVSE2.dll b/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVSE2.dll deleted file mode 100644 index 8129116fd4..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/dll/x86/pthreadVSE2.dll and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/include/pthread.h b/bridge/third_party/quickjs/compat/win32/pthreads/include/pthread.h deleted file mode 100644 index cad8bc541a..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/include/pthread.h +++ /dev/null @@ -1,1368 +0,0 @@ -/* This is an implementation of the threads API of POSIX 1003.1-2001. - * - * -------------------------------------------------------------------------- - * - * Pthreads-win32 - POSIX Threads Library for Win32 - * Copyright(C) 1998 John E. Bossom - * Copyright(C) 1999,2005 Pthreads-win32 contributors - * - * Contact Email: rpj@callisto.canberra.edu.au - * - * The current list of contributors is contained - * in the file CONTRIBUTORS included with the source - * code distribution. The list can also be seen at the - * following World Wide Web location: - * http://sources.redhat.com/pthreads-win32/contributors.html - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library in the file COPYING.LIB; - * if not, write to the Free Software Foundation, Inc., - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - */ - -#if !defined( PTHREAD_H ) -#define PTHREAD_H - -/* - * See the README file for an explanation of the pthreads-win32 version - * numbering scheme and how the DLL is named etc. - */ -#define PTW32_VERSION 2,9,1,0 -#define PTW32_VERSION_STRING "2, 9, 1, 0\0" - -/* There are three implementations of cancel cleanup. - * Note that pthread.h is included in both application - * compilation units and also internally for the library. - * The code here and within the library aims to work - * for all reasonable combinations of environments. - * - * The three implementations are: - * - * WIN32 SEH - * C - * C++ - * - * Please note that exiting a push/pop block via - * "return", "exit", "break", or "continue" will - * lead to different behaviour amongst applications - * depending upon whether the library was built - * using SEH, C++, or C. For example, a library built - * with SEH will call the cleanup routine, while both - * C++ and C built versions will not. - */ - -/* - * Define defaults for cleanup code. - * Note: Unless the build explicitly defines one of the following, then - * we default to standard C style cleanup. This style uses setjmp/longjmp - * in the cancelation and thread exit implementations and therefore won't - * do stack unwinding if linked to applications that have it (e.g. - * C++ apps). This is currently consistent with most/all commercial Unix - * POSIX threads implementations. - */ -#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __CLEANUP_C ) -# define __CLEANUP_C -#endif - -#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC_MSC)) -#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compiler. -#endif - -/* - * Stop here if we are being included by the resource compiler. - */ -#if !defined(RC_INVOKED) - -#undef PTW32_LEVEL - -#if defined(_POSIX_SOURCE) -#define PTW32_LEVEL 0 -/* Early POSIX */ -#endif - -#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 -#undef PTW32_LEVEL -#define PTW32_LEVEL 1 -/* Include 1b, 1c and 1d */ -#endif - -#if defined(INCLUDE_NP) -#undef PTW32_LEVEL -#define PTW32_LEVEL 2 -/* Include Non-Portable extensions */ -#endif - -#define PTW32_LEVEL_MAX 3 - -#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 ) || !defined(PTW32_LEVEL) -#define PTW32_LEVEL PTW32_LEVEL_MAX -/* Include everything */ -#endif - -#if defined(_UWIN) -# define HAVE_STRUCT_TIMESPEC 1 -# define HAVE_SIGNAL_H 1 -# undef HAVE_PTW32_CONFIG_H -# pragma comment(lib, "pthread") -#endif - -/* - * ------------------------------------------------------------- - * - * - * Module: pthread.h - * - * Purpose: - * Provides an implementation of PThreads based upon the - * standard: - * - * POSIX 1003.1-2001 - * and - * The Single Unix Specification version 3 - * - * (these two are equivalent) - * - * in order to enhance code portability between Windows, - * various commercial Unix implementations, and Linux. - * - * See the ANNOUNCE file for a full list of conforming - * routines and defined constants, and a list of missing - * routines and constants not defined in this implementation. - * - * Authors: - * There have been many contributors to this library. - * The initial implementation was contributed by - * John Bossom, and several others have provided major - * sections or revisions of parts of the implementation. - * Often significant effort has been contributed to - * find and fix important bugs and other problems to - * improve the reliability of the library, which sometimes - * is not reflected in the amount of code which changed as - * result. - * As much as possible, the contributors are acknowledged - * in the ChangeLog file in the source code distribution - * where their changes are noted in detail. - * - * Contributors are listed in the CONTRIBUTORS file. - * - * As usual, all bouquets go to the contributors, and all - * brickbats go to the project maintainer. - * - * Maintainer: - * The code base for this project is coordinated and - * eventually pre-tested, packaged, and made available by - * - * Ross Johnson - * - * QA Testers: - * Ultimately, the library is tested in the real world by - * a host of competent and demanding scientists and - * engineers who report bugs and/or provide solutions - * which are then fixed or incorporated into subsequent - * versions of the library. Each time a bug is fixed, a - * test case is written to prove the fix and ensure - * that later changes to the code don't reintroduce the - * same error. The number of test cases is slowly growing - * and therefore so is the code reliability. - * - * Compliance: - * See the file ANNOUNCE for the list of implemented - * and not-implemented routines and defined options. - * Of course, these are all defined is this file as well. - * - * Web site: - * The source code and other information about this library - * are available from - * - * http://sources.redhat.com/pthreads-win32/ - * - * ------------------------------------------------------------- - */ - -/* Try to avoid including windows.h */ -#if (defined(__MINGW64__) || defined(__MINGW32__)) && defined(__cplusplus) -#define PTW32_INCLUDE_WINDOWS_H -#endif - -#if defined(PTW32_INCLUDE_WINDOWS_H) -#include -#endif - -#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__) -/* - * VC++6.0 or early compiler's header has no DWORD_PTR type. - */ -typedef unsigned long DWORD_PTR; -typedef unsigned long ULONG_PTR; -#endif -/* - * ----------------- - * autoconf switches - * ----------------- - */ - -#if defined(HAVE_PTW32_CONFIG_H) -#include "config.h" -#endif /* HAVE_PTW32_CONFIG_H */ - -#if !defined(NEED_FTIME) -#include -#else /* NEED_FTIME */ -/* use native WIN32 time API */ -#endif /* NEED_FTIME */ - -#if defined(HAVE_SIGNAL_H) -#include -#endif /* HAVE_SIGNAL_H */ - -#include - -/* - * Boolean values to make us independent of system includes. - */ -enum { - PTW32_FALSE = 0, - PTW32_TRUE = (! PTW32_FALSE) -}; - -/* - * This is a duplicate of what is in the autoconf config.h, - * which is only used when building the pthread-win32 libraries. - */ - -#if !defined(PTW32_CONFIG_H) -# if defined(WINCE) -# define NEED_ERRNO -# define NEED_SEM -# endif -# if defined(__MINGW64__) -# define HAVE_STRUCT_TIMESPEC -# define HAVE_MODE_T -# elif defined(_UWIN) || defined(__MINGW32__) -# define HAVE_MODE_T -# endif -#endif - -/* - * - */ - -#if PTW32_LEVEL >= PTW32_LEVEL_MAX -#if defined(NEED_ERRNO) -#include "need_errno.h" -#else -#include -#endif -#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ - -/* - * Several systems don't define some error numbers. - */ -#if !defined(ENOTSUP) -# define ENOTSUP 48 /* This is the value in Solaris. */ -#endif - -#if !defined(ETIMEDOUT) -# define ETIMEDOUT 10060 /* Same as WSAETIMEDOUT */ -#endif - -#if !defined(ENOSYS) -# define ENOSYS 140 /* Semi-arbitrary value */ -#endif - -#if !defined(EDEADLK) -# if defined(EDEADLOCK) -# define EDEADLK EDEADLOCK -# else -# define EDEADLK 36 /* This is the value in MSVC. */ -# endif -#endif - -/* POSIX 2008 - related to robust mutexes */ -#if !defined(EOWNERDEAD) -# define EOWNERDEAD 43 -#endif -#if !defined(ENOTRECOVERABLE) -# define ENOTRECOVERABLE 44 -#endif - -#include "sched.h" - -/* - * To avoid including windows.h we define only those things that we - * actually need from it. - */ -#if !defined(PTW32_INCLUDE_WINDOWS_H) -#if !defined(HANDLE) -# define PTW32__HANDLE_DEF -# define HANDLE void * -#endif -#if !defined(DWORD) -# define PTW32__DWORD_DEF -# define DWORD unsigned long -#endif -#endif - -#if !defined(HAVE_STRUCT_TIMESPEC) -#define HAVE_STRUCT_TIMESPEC -#if !defined(_TIMESPEC_DEFINED) -#define _TIMESPEC_DEFINED -struct timespec { - time_t tv_sec; - long tv_nsec; -}; -#endif /* _TIMESPEC_DEFINED */ -#endif /* HAVE_STRUCT_TIMESPEC */ - -#if !defined(SIG_BLOCK) -#define SIG_BLOCK 0 -#endif /* SIG_BLOCK */ - -#if !defined(SIG_UNBLOCK) -#define SIG_UNBLOCK 1 -#endif /* SIG_UNBLOCK */ - -#if !defined(SIG_SETMASK) -#define SIG_SETMASK 2 -#endif /* SIG_SETMASK */ - -#if defined(__cplusplus) -extern "C" -{ -#endif /* __cplusplus */ - -/* - * ------------------------------------------------------------- - * - * POSIX 1003.1-2001 Options - * ========================= - * - * Options are normally set in , which is not provided - * with pthreads-win32. - * - * For conformance with the Single Unix Specification (version 3), all of the - * options below are defined, and have a value of either -1 (not supported) - * or 200112L (supported). - * - * These options can neither be left undefined nor have a value of 0, because - * either indicates that sysconf(), which is not implemented, may be used at - * runtime to check the status of the option. - * - * _POSIX_THREADS (== 200112L) - * If == 200112L, you can use threads - * - * _POSIX_THREAD_ATTR_STACKSIZE (== 200112L) - * If == 200112L, you can control the size of a thread's - * stack - * pthread_attr_getstacksize - * pthread_attr_setstacksize - * - * _POSIX_THREAD_ATTR_STACKADDR (== -1) - * If == 200112L, you can allocate and control a thread's - * stack. If not supported, the following functions - * will return ENOSYS, indicating they are not - * supported: - * pthread_attr_getstackaddr - * pthread_attr_setstackaddr - * - * _POSIX_THREAD_PRIORITY_SCHEDULING (== -1) - * If == 200112L, you can use realtime scheduling. - * This option indicates that the behaviour of some - * implemented functions conforms to the additional TPS - * requirements in the standard. E.g. rwlocks favour - * writers over readers when threads have equal priority. - * - * _POSIX_THREAD_PRIO_INHERIT (== -1) - * If == 200112L, you can create priority inheritance - * mutexes. - * pthread_mutexattr_getprotocol + - * pthread_mutexattr_setprotocol + - * - * _POSIX_THREAD_PRIO_PROTECT (== -1) - * If == 200112L, you can create priority ceiling mutexes - * Indicates the availability of: - * pthread_mutex_getprioceiling - * pthread_mutex_setprioceiling - * pthread_mutexattr_getprioceiling - * pthread_mutexattr_getprotocol + - * pthread_mutexattr_setprioceiling - * pthread_mutexattr_setprotocol + - * - * _POSIX_THREAD_PROCESS_SHARED (== -1) - * If set, you can create mutexes and condition - * variables that can be shared with another - * process.If set, indicates the availability - * of: - * pthread_mutexattr_getpshared - * pthread_mutexattr_setpshared - * pthread_condattr_getpshared - * pthread_condattr_setpshared - * - * _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L) - * If == 200112L you can use the special *_r library - * functions that provide thread-safe behaviour - * - * _POSIX_READER_WRITER_LOCKS (== 200112L) - * If == 200112L, you can use read/write locks - * - * _POSIX_SPIN_LOCKS (== 200112L) - * If == 200112L, you can use spin locks - * - * _POSIX_BARRIERS (== 200112L) - * If == 200112L, you can use barriers - * - * + These functions provide both 'inherit' and/or - * 'protect' protocol, based upon these macro - * settings. - * - * ------------------------------------------------------------- - */ - -/* - * POSIX Options - */ -#undef _POSIX_THREADS -#define _POSIX_THREADS 200809L - -#undef _POSIX_READER_WRITER_LOCKS -#define _POSIX_READER_WRITER_LOCKS 200809L - -#undef _POSIX_SPIN_LOCKS -#define _POSIX_SPIN_LOCKS 200809L - -#undef _POSIX_BARRIERS -#define _POSIX_BARRIERS 200809L - -#undef _POSIX_THREAD_SAFE_FUNCTIONS -#define _POSIX_THREAD_SAFE_FUNCTIONS 200809L - -#undef _POSIX_THREAD_ATTR_STACKSIZE -#define _POSIX_THREAD_ATTR_STACKSIZE 200809L - -/* - * The following options are not supported - */ -#undef _POSIX_THREAD_ATTR_STACKADDR -#define _POSIX_THREAD_ATTR_STACKADDR -1 - -#undef _POSIX_THREAD_PRIO_INHERIT -#define _POSIX_THREAD_PRIO_INHERIT -1 - -#undef _POSIX_THREAD_PRIO_PROTECT -#define _POSIX_THREAD_PRIO_PROTECT -1 - -/* TPS is not fully supported. */ -#undef _POSIX_THREAD_PRIORITY_SCHEDULING -#define _POSIX_THREAD_PRIORITY_SCHEDULING -1 - -#undef _POSIX_THREAD_PROCESS_SHARED -#define _POSIX_THREAD_PROCESS_SHARED -1 - - -/* - * POSIX 1003.1-2001 Limits - * =========================== - * - * These limits are normally set in , which is not provided with - * pthreads-win32. - * - * PTHREAD_DESTRUCTOR_ITERATIONS - * Maximum number of attempts to destroy - * a thread's thread-specific data on - * termination (must be at least 4) - * - * PTHREAD_KEYS_MAX - * Maximum number of thread-specific data keys - * available per process (must be at least 128) - * - * PTHREAD_STACK_MIN - * Minimum supported stack size for a thread - * - * PTHREAD_THREADS_MAX - * Maximum number of threads supported per - * process (must be at least 64). - * - * SEM_NSEMS_MAX - * The maximum number of semaphores a process can have. - * (must be at least 256) - * - * SEM_VALUE_MAX - * The maximum value a semaphore can have. - * (must be at least 32767) - * - */ -#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS -#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4 - -#undef PTHREAD_DESTRUCTOR_ITERATIONS -#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_ITERATIONS - -#undef _POSIX_THREAD_KEYS_MAX -#define _POSIX_THREAD_KEYS_MAX 128 - -#undef PTHREAD_KEYS_MAX -#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX - -#undef PTHREAD_STACK_MIN -#define PTHREAD_STACK_MIN 0 - -#undef _POSIX_THREAD_THREADS_MAX -#define _POSIX_THREAD_THREADS_MAX 64 - - /* Arbitrary value */ -#undef PTHREAD_THREADS_MAX -#define PTHREAD_THREADS_MAX 2019 - -#undef _POSIX_SEM_NSEMS_MAX -#define _POSIX_SEM_NSEMS_MAX 256 - - /* Arbitrary value */ -#undef SEM_NSEMS_MAX -#define SEM_NSEMS_MAX 1024 - -#undef _POSIX_SEM_VALUE_MAX -#define _POSIX_SEM_VALUE_MAX 32767 - -#undef SEM_VALUE_MAX -#define SEM_VALUE_MAX INT_MAX - - -#if defined(__GNUC__) && !defined(__declspec) -# error Please upgrade your GNU compiler to one that supports __declspec. -#endif - -/* - * When building the library, you should define PTW32_BUILD so that - * the variables/functions are exported correctly. When using the library, - * do NOT define PTW32_BUILD, and then the variables/functions will - * be imported correctly. - */ -#if !defined(PTW32_STATIC_LIB) -# if defined(PTW32_BUILD) -# define PTW32_DLLPORT __declspec (dllexport) -# else -# define PTW32_DLLPORT __declspec (dllimport) -# endif -#else -# define PTW32_DLLPORT -#endif - -/* - * The Open Watcom C/C++ compiler uses a non-standard calling convention - * that passes function args in registers unless __cdecl is explicitly specified - * in exposed function prototypes. - * - * We force all calls to cdecl even though this could slow Watcom code down - * slightly. If you know that the Watcom compiler will be used to build both - * the DLL and application, then you can probably define this as a null string. - * Remember that pthread.h (this file) is used for both the DLL and application builds. - */ -#define PTW32_CDECL __cdecl - -#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX -# include -#else -/* - * Generic handle type - intended to extend uniqueness beyond - * that available with a simple pointer. It should scale for either - * IA-32 or IA-64. - */ -typedef struct { - void * p; /* Pointer to actual object */ - unsigned int x; /* Extra information - reuse count etc */ -} ptw32_handle_t; - -typedef ptw32_handle_t pthread_t; -typedef struct pthread_attr_t_ * pthread_attr_t; -typedef struct pthread_once_t_ pthread_once_t; -typedef struct pthread_key_t_ * pthread_key_t; -typedef struct pthread_mutex_t_ * pthread_mutex_t; -typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t; -typedef struct pthread_cond_t_ * pthread_cond_t; -typedef struct pthread_condattr_t_ * pthread_condattr_t; -#endif -typedef struct pthread_rwlock_t_ * pthread_rwlock_t; -typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t; -typedef struct pthread_spinlock_t_ * pthread_spinlock_t; -typedef struct pthread_barrier_t_ * pthread_barrier_t; -typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t; - -/* - * ==================== - * ==================== - * POSIX Threads - * ==================== - * ==================== - */ - -enum { -/* - * pthread_attr_{get,set}detachstate - */ - PTHREAD_CREATE_JOINABLE = 0, /* Default */ - PTHREAD_CREATE_DETACHED = 1, - -/* - * pthread_attr_{get,set}inheritsched - */ - PTHREAD_INHERIT_SCHED = 0, - PTHREAD_EXPLICIT_SCHED = 1, /* Default */ - -/* - * pthread_{get,set}scope - */ - PTHREAD_SCOPE_PROCESS = 0, - PTHREAD_SCOPE_SYSTEM = 1, /* Default */ - -/* - * pthread_setcancelstate paramters - */ - PTHREAD_CANCEL_ENABLE = 0, /* Default */ - PTHREAD_CANCEL_DISABLE = 1, - -/* - * pthread_setcanceltype parameters - */ - PTHREAD_CANCEL_ASYNCHRONOUS = 0, - PTHREAD_CANCEL_DEFERRED = 1, /* Default */ - -/* - * pthread_mutexattr_{get,set}pshared - * pthread_condattr_{get,set}pshared - */ - PTHREAD_PROCESS_PRIVATE = 0, - PTHREAD_PROCESS_SHARED = 1, - -/* - * pthread_mutexattr_{get,set}robust - */ - PTHREAD_MUTEX_STALLED = 0, /* Default */ - PTHREAD_MUTEX_ROBUST = 1, - -/* - * pthread_barrier_wait - */ - PTHREAD_BARRIER_SERIAL_THREAD = -1 -}; - -/* - * ==================== - * ==================== - * Cancelation - * ==================== - * ==================== - */ -#define PTHREAD_CANCELED ((void *)(size_t) -1) - - -/* - * ==================== - * ==================== - * Once Key - * ==================== - * ==================== - */ -#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0} - -struct pthread_once_t_ -{ - int done; /* indicates if user function has been executed */ - void * lock; - int reserved1; - int reserved2; -}; - - -/* - * ==================== - * ==================== - * Object initialisers - * ==================== - * ==================== - */ -#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -1) -#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -2) -#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -3) - -/* - * Compatibility with LinuxThreads - */ -#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INITIALIZER -#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_INITIALIZER - -#define PTHREAD_COND_INITIALIZER ((pthread_cond_t)(size_t) -1) - -#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t)(size_t) -1) - -#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t)(size_t) -1) - - -/* - * Mutex types. - */ -enum -{ - /* Compatibility with LinuxThreads */ - PTHREAD_MUTEX_FAST_NP, - PTHREAD_MUTEX_RECURSIVE_NP, - PTHREAD_MUTEX_ERRORCHECK_NP, - PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP, - PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP, - /* For compatibility with POSIX */ - PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP, - PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP, - PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP, - PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL -}; - - -typedef struct ptw32_cleanup_t ptw32_cleanup_t; - -#if defined(_MSC_VER) -/* Disable MSVC 'anachronism used' warning */ -#pragma warning( disable : 4229 ) -#endif - -typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *); - -#if defined(_MSC_VER) -#pragma warning( default : 4229 ) -#endif - -struct ptw32_cleanup_t -{ - ptw32_cleanup_callback_t routine; - void *arg; - struct ptw32_cleanup_t *prev; -}; - -#if defined(__CLEANUP_SEH) - /* - * WIN32 SEH version of cancel cleanup. - */ - -#define pthread_cleanup_push( _rout, _arg ) \ - { \ - ptw32_cleanup_t _cleanup; \ - \ - _cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \ - _cleanup.arg = (_arg); \ - __try \ - { \ - -#define pthread_cleanup_pop( _execute ) \ - } \ - __finally \ - { \ - if( _execute || AbnormalTermination()) \ - { \ - (*(_cleanup.routine))( _cleanup.arg ); \ - } \ - } \ - } - -#else /* __CLEANUP_SEH */ - -#if defined(__CLEANUP_C) - - /* - * C implementation of PThreads cancel cleanup - */ - -#define pthread_cleanup_push( _rout, _arg ) \ - { \ - ptw32_cleanup_t _cleanup; \ - \ - ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rout), (_arg) ); \ - -#define pthread_cleanup_pop( _execute ) \ - (void) ptw32_pop_cleanup( _execute ); \ - } - -#else /* __CLEANUP_C */ - -#if defined(__CLEANUP_CXX) - - /* - * C++ version of cancel cleanup. - * - John E. Bossom. - */ - - class PThreadCleanup { - /* - * PThreadCleanup - * - * Purpose - * This class is a C++ helper class that is - * used to implement pthread_cleanup_push/ - * pthread_cleanup_pop. - * The destructor of this class automatically - * pops the pushed cleanup routine regardless - * of how the code exits the scope - * (i.e. such as by an exception) - */ - ptw32_cleanup_callback_t cleanUpRout; - void * obj; - int executeIt; - - public: - PThreadCleanup() : - cleanUpRout( 0 ), - obj( 0 ), - executeIt( 0 ) - /* - * No cleanup performed - */ - { - } - - PThreadCleanup( - ptw32_cleanup_callback_t routine, - void * arg ) : - cleanUpRout( routine ), - obj( arg ), - executeIt( 1 ) - /* - * Registers a cleanup routine for 'arg' - */ - { - } - - ~PThreadCleanup() - { - if ( executeIt && ((void *) cleanUpRout != (void *) 0) ) - { - (void) (*cleanUpRout)( obj ); - } - } - - void execute( int exec ) - { - executeIt = exec; - } - }; - - /* - * C++ implementation of PThreads cancel cleanup; - * This implementation takes advantage of a helper - * class who's destructor automatically calls the - * cleanup routine if we exit our scope weirdly - */ -#define pthread_cleanup_push( _rout, _arg ) \ - { \ - PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \ - (void *) (_arg) ); - -#define pthread_cleanup_pop( _execute ) \ - cleanup.execute( _execute ); \ - } - -#else - -#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined. - -#endif /* __CLEANUP_CXX */ - -#endif /* __CLEANUP_C */ - -#endif /* __CLEANUP_SEH */ - -/* - * =============== - * =============== - * Methods - * =============== - * =============== - */ - -/* - * PThread Attribute Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_attr_t * attr, - int *detachstate); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr_t * attr, - void **stackaddr); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr_t * attr, - size_t * stacksize); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t * attr, - int detachstate); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * attr, - void *stackaddr); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * attr, - size_t stacksize); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_attr_t *attr, - struct sched_param *param); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *attr, - const struct sched_param *param); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *, - int); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (const pthread_attr_t *, - int *); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t * attr, - int inheritsched); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(const pthread_attr_t * attr, - int * inheritsched); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *, - int); - -PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *, - int *); - -/* - * PThread Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid, - const pthread_attr_t * attr, - void *(PTW32_CDECL *start) (void *), - void *arg); - -PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid); - -PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1, - pthread_t t2); - -PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr); - -PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread, - void **value_ptr); - -PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void); - -PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread); - -PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state, - int *oldstate); - -PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type, - int *oldtype); - -PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void); - -PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control, - void (PTW32_CDECL *init_routine) (void)); - -#if PTW32_LEVEL >= PTW32_LEVEL_MAX -PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute); - -PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanup, - ptw32_cleanup_callback_t routine, - void *arg); -#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ - -/* - * Thread Specific Data Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key, - void (PTW32_CDECL *destructor) (void *)); - -PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key); - -PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key, - const void *value); - -PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key); - - -/* - * Mutex Attribute Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_mutexattr_t - * attr, - int *pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexattr_t * attr, - int pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind); -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (const pthread_mutexattr_t * attr, int *kind); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setrobust( - pthread_mutexattr_t *attr, - int robust); -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getrobust( - const pthread_mutexattr_t * attr, - int * robust); - -/* - * Barrier Attribute Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barrierattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread_barrierattr_t - * attr, - int *pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barrierattr_t * attr, - int pshared); - -/* - * Mutex Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex, - const pthread_mutexattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mutex); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t * mutex, - const struct timespec *abstime); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mutex); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex); - -PTW32_DLLPORT int PTW32_CDECL pthread_mutex_consistent (pthread_mutex_t * mutex); - -/* - * Spinlock Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock, int pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * lock); - -/* - * Barrier Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * barrier, - const pthread_barrierattr_t * attr, - unsigned int count); - -PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t * barrier); - -PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * barrier); - -/* - * Condition Variable Attribute Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_condattr_t * attr, - int *pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr_t * attr, - int pshared); - -/* - * Condition Variable Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond, - const pthread_condattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond); - -PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond, - pthread_mutex_t * mutex); - -PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond, - pthread_mutex_t * mutex, - const struct timespec *abstime); - -PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond); - -PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond); - -/* - * Scheduling - */ -PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread, - int policy, - const struct sched_param *param); - -PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread, - int *policy, - struct sched_param *param); - -PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int); - -PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void); - -/* - * Read-Write Lock Functions - */ -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock, - const pthread_rwlockattr_t *attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *lock, - const struct timespec *abstime); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *lock, - const struct timespec *abstime); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr, - int *pshared); - -PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr, - int pshared); - -#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 - -/* - * Signal Functions. Should be defined in but MSVC and MinGW32 - * already have signal.h that don't define these. - */ -PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig); - -/* - * Non-portable functions - */ - -/* - * Compatibility with Linux. - */ -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr, - int kind); -PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr, - int *kind); - -/* - * Possibly supported by other POSIX threads implementations - */ -PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval); -PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void); -PTW32_DLLPORT unsigned __int64 PTW32_CDECL pthread_getunique_np(pthread_t thread); - -/* - * Useful if an application wants to statically link - * the lib rather than load the DLL at run-time. - */ -PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void); -PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void); -PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void); -PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void); - -/* - * Features that are auto-detected at load/run time. - */ -PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int); -enum ptw32_features { - PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it. */ - PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked threads. */ -}; - -/* - * Register a system time change with the library. - * Causes the library to perform various functions - * in response to the change. Should be called whenever - * the application's top level window receives a - * WM_TIMECHANGE message. It can be passed directly to - * pthread_create() as a new thread if desired. - */ -PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *); - -#endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */ - -#if PTW32_LEVEL >= PTW32_LEVEL_MAX - -/* - * Returns the Win32 HANDLE for the POSIX thread. - */ -PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t thread); -/* - * Returns the win32 thread ID for POSIX thread. - */ -PTW32_DLLPORT DWORD PTW32_CDECL pthread_getw32threadid_np (pthread_t thread); - - -/* - * Protected Methods - * - * This function blocks until the given WIN32 handle - * is signaled or pthread_cancel had been called. - * This function allows the caller to hook into the - * PThreads cancel mechanism. It is implemented using - * - * WaitForMultipleObjects - * - * on 'waitHandle' and a manually reset WIN32 Event - * used to implement pthread_cancel. The 'timeout' - * argument to TimedWait is simply passed to - * WaitForMultipleObjects. - */ -PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle); -PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle, - DWORD timeout); - -#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ - -/* - * Thread-Safe C Runtime Library Mappings. - */ -#if !defined(_UWIN) -# if defined(NEED_ERRNO) - PTW32_DLLPORT int * PTW32_CDECL _errno( void ); -# else -# if !defined(errno) -# if (defined(_MT) || defined(_DLL)) - __declspec(dllimport) extern int * __cdecl _errno(void); -# define errno (*_errno()) -# endif -# endif -# endif -#endif - -/* - * Some compiler environments don't define some things. - */ -#if defined(__BORLANDC__) -# define _ftime ftime -# define _timeb timeb -#endif - -#if defined(__cplusplus) - -/* - * Internal exceptions - */ -class ptw32_exception {}; -class ptw32_exception_cancel : public ptw32_exception {}; -class ptw32_exception_exit : public ptw32_exception {}; - -#endif - -#if PTW32_LEVEL >= PTW32_LEVEL_MAX - -/* FIXME: This is only required if the library was built using SEH */ -/* - * Get internal SEH tag - */ -PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void); - -#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ - -#if !defined(PTW32_BUILD) - -#if defined(__CLEANUP_SEH) - -/* - * Redefine the SEH __except keyword to ensure that applications - * propagate our internal exceptions up to the library's internal handlers. - */ -#define __except( E ) \ - __except( ( GetExceptionCode() == ptw32_get_exception_services_code() ) \ - ? EXCEPTION_CONTINUE_SEARCH : ( E ) ) - -#endif /* __CLEANUP_SEH */ - -#if defined(__CLEANUP_CXX) - -/* - * Redefine the C++ catch keyword to ensure that applications - * propagate our internal exceptions up to the library's internal handlers. - */ -#if defined(_MSC_VER) - /* - * WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll' - * if you want Pthread-Win32 cancelation and pthread_exit to work. - */ - -#if !defined(PtW32NoCatchWarn) - -#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this message.") -#pragma message("------------------------------------------------------------------") -#pragma message("When compiling applications with MSVC++ and C++ exception handling:") -#pragma message(" Replace any 'catch( ... )' in routines called from POSIX threads") -#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thread") -#pragma message(" cancelation and pthread_exit to work. For example:") -#pragma message("") -#pragma message(" #if defined(PtW32CatchAll)") -#pragma message(" PtW32CatchAll") -#pragma message(" #else") -#pragma message(" catch(...)") -#pragma message(" #endif") -#pragma message(" {") -#pragma message(" /* Catchall block processing */") -#pragma message(" }") -#pragma message("------------------------------------------------------------------") - -#endif - -#define PtW32CatchAll \ - catch( ptw32_exception & ) { throw; } \ - catch( ... ) - -#else /* _MSC_VER */ - -#define catch( E ) \ - catch( ptw32_exception & ) { throw; } \ - catch( E ) - -#endif /* _MSC_VER */ - -#endif /* __CLEANUP_CXX */ - -#endif /* ! PTW32_BUILD */ - -#if defined(__cplusplus) -} /* End of extern "C" */ -#endif /* __cplusplus */ - -#if defined(PTW32__HANDLE_DEF) -# undef HANDLE -#endif -#if defined(PTW32__DWORD_DEF) -# undef DWORD -#endif - -#undef PTW32_LEVEL -#undef PTW32_LEVEL_MAX - -#endif /* ! RC_INVOKED */ - -#endif /* PTHREAD_H */ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/include/sched.h b/bridge/third_party/quickjs/compat/win32/pthreads/include/sched.h deleted file mode 100644 index f36a97a66b..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/include/sched.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Module: sched.h - * - * Purpose: - * Provides an implementation of POSIX realtime extensions - * as defined in - * - * POSIX 1003.1b-1993 (POSIX.1b) - * - * -------------------------------------------------------------------------- - * - * Pthreads-win32 - POSIX Threads Library for Win32 - * Copyright(C) 1998 John E. Bossom - * Copyright(C) 1999,2005 Pthreads-win32 contributors - * - * Contact Email: rpj@callisto.canberra.edu.au - * - * The current list of contributors is contained - * in the file CONTRIBUTORS included with the source - * code distribution. The list can also be seen at the - * following World Wide Web location: - * http://sources.redhat.com/pthreads-win32/contributors.html - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library in the file COPYING.LIB; - * if not, write to the Free Software Foundation, Inc., - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - */ -#if !defined(_SCHED_H) -#define _SCHED_H - -#undef PTW32_SCHED_LEVEL - -#if defined(_POSIX_SOURCE) -#define PTW32_SCHED_LEVEL 0 -/* Early POSIX */ -#endif - -#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 -#undef PTW32_SCHED_LEVEL -#define PTW32_SCHED_LEVEL 1 -/* Include 1b, 1c and 1d */ -#endif - -#if defined(INCLUDE_NP) -#undef PTW32_SCHED_LEVEL -#define PTW32_SCHED_LEVEL 2 -/* Include Non-Portable extensions */ -#endif - -#define PTW32_SCHED_LEVEL_MAX 3 - -#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 ) || !defined(PTW32_SCHED_LEVEL) -#define PTW32_SCHED_LEVEL PTW32_SCHED_LEVEL_MAX -/* Include everything */ -#endif - - -#if defined(__GNUC__) && !defined(__declspec) -# error Please upgrade your GNU compiler to one that supports __declspec. -#endif - -/* - * When building the library, you should define PTW32_BUILD so that - * the variables/functions are exported correctly. When using the library, - * do NOT define PTW32_BUILD, and then the variables/functions will - * be imported correctly. - */ -#if !defined(PTW32_STATIC_LIB) -# if defined(PTW32_BUILD) -# define PTW32_DLLPORT __declspec (dllexport) -# else -# define PTW32_DLLPORT __declspec (dllimport) -# endif -#else -# define PTW32_DLLPORT -#endif - -/* - * This is a duplicate of what is in the autoconf config.h, - * which is only used when building the pthread-win32 libraries. - */ - -#if !defined(PTW32_CONFIG_H) -# if defined(WINCE) -# define NEED_ERRNO -# define NEED_SEM -# endif -# if defined(__MINGW64__) -# define HAVE_STRUCT_TIMESPEC -# define HAVE_MODE_T -# elif defined(_UWIN) || defined(__MINGW32__) -# define HAVE_MODE_T -# endif -#endif - -/* - * - */ - -#if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX -#if defined(NEED_ERRNO) -#include "need_errno.h" -#else -#include -#endif -#endif /* PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX */ - -#if (defined(__MINGW64__) || defined(__MINGW32__)) || defined(_UWIN) -# if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX -/* For pid_t */ -# include -/* Required by Unix 98 */ -# include -# else - typedef int pid_t; -# endif -#else - typedef int pid_t; -#endif - -/* Thread scheduling policies */ - -enum { - SCHED_OTHER = 0, - SCHED_FIFO, - SCHED_RR, - SCHED_MIN = SCHED_OTHER, - SCHED_MAX = SCHED_RR -}; - -struct sched_param { - int sched_priority; -}; - -#if defined(__cplusplus) -extern "C" -{ -#endif /* __cplusplus */ - -PTW32_DLLPORT int __cdecl sched_yield (void); - -PTW32_DLLPORT int __cdecl sched_get_priority_min (int policy); - -PTW32_DLLPORT int __cdecl sched_get_priority_max (int policy); - -PTW32_DLLPORT int __cdecl sched_setscheduler (pid_t pid, int policy); - -PTW32_DLLPORT int __cdecl sched_getscheduler (pid_t pid); - -/* - * Note that this macro returns ENOTSUP rather than - * ENOSYS as might be expected. However, returning ENOSYS - * should mean that sched_get_priority_{min,max} are - * not implemented as well as sched_rr_get_interval. - * This is not the case, since we just don't support - * round-robin scheduling. Therefore I have chosen to - * return the same value as sched_setscheduler when - * SCHED_RR is passed to it. - */ -#define sched_rr_get_interval(_pid, _interval) \ - ( errno = ENOTSUP, (int) -1 ) - - -#if defined(__cplusplus) -} /* End of extern "C" */ -#endif /* __cplusplus */ - -#undef PTW32_SCHED_LEVEL -#undef PTW32_SCHED_LEVEL_MAX - -#endif /* !_SCHED_H */ - diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/include/semaphore.h b/bridge/third_party/quickjs/compat/win32/pthreads/include/semaphore.h deleted file mode 100644 index c6e9407e25..0000000000 --- a/bridge/third_party/quickjs/compat/win32/pthreads/include/semaphore.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Module: semaphore.h - * - * Purpose: - * Semaphores aren't actually part of the PThreads standard. - * They are defined by the POSIX Standard: - * - * POSIX 1003.1b-1993 (POSIX.1b) - * - * -------------------------------------------------------------------------- - * - * Pthreads-win32 - POSIX Threads Library for Win32 - * Copyright(C) 1998 John E. Bossom - * Copyright(C) 1999,2005 Pthreads-win32 contributors - * - * Contact Email: rpj@callisto.canberra.edu.au - * - * The current list of contributors is contained - * in the file CONTRIBUTORS included with the source - * code distribution. The list can also be seen at the - * following World Wide Web location: - * http://sources.redhat.com/pthreads-win32/contributors.html - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library in the file COPYING.LIB; - * if not, write to the Free Software Foundation, Inc., - * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - */ -#if !defined( SEMAPHORE_H ) -#define SEMAPHORE_H - -#undef PTW32_SEMAPHORE_LEVEL - -#if defined(_POSIX_SOURCE) -#define PTW32_SEMAPHORE_LEVEL 0 -/* Early POSIX */ -#endif - -#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 -#undef PTW32_SEMAPHORE_LEVEL -#define PTW32_SEMAPHORE_LEVEL 1 -/* Include 1b, 1c and 1d */ -#endif - -#if defined(INCLUDE_NP) -#undef PTW32_SEMAPHORE_LEVEL -#define PTW32_SEMAPHORE_LEVEL 2 -/* Include Non-Portable extensions */ -#endif - -#define PTW32_SEMAPHORE_LEVEL_MAX 3 - -#if !defined(PTW32_SEMAPHORE_LEVEL) -#define PTW32_SEMAPHORE_LEVEL PTW32_SEMAPHORE_LEVEL_MAX -/* Include everything */ -#endif - -#if defined(__GNUC__) && ! defined (__declspec) -# error Please upgrade your GNU compiler to one that supports __declspec. -#endif - -/* - * When building the library, you should define PTW32_BUILD so that - * the variables/functions are exported correctly. When using the library, - * do NOT define PTW32_BUILD, and then the variables/functions will - * be imported correctly. - */ -#if !defined(PTW32_STATIC_LIB) -# if defined(PTW32_BUILD) -# define PTW32_DLLPORT __declspec (dllexport) -# else -# define PTW32_DLLPORT __declspec (dllimport) -# endif -#else -# define PTW32_DLLPORT -#endif - -/* - * This is a duplicate of what is in the autoconf config.h, - * which is only used when building the pthread-win32 libraries. - */ - -#if !defined(PTW32_CONFIG_H) -# if defined(WINCE) -# define NEED_ERRNO -# define NEED_SEM -# endif -# if defined(__MINGW64__) -# define HAVE_STRUCT_TIMESPEC -# define HAVE_MODE_T -# elif defined(_UWIN) || defined(__MINGW32__) -# define HAVE_MODE_T -# endif -#endif - -/* - * - */ - -#if PTW32_SEMAPHORE_LEVEL >= PTW32_SEMAPHORE_LEVEL_MAX -#if defined(NEED_ERRNO) -#include "need_errno.h" -#else -#include -#endif -#endif /* PTW32_SEMAPHORE_LEVEL >= PTW32_SEMAPHORE_LEVEL_MAX */ - -#define _POSIX_SEMAPHORES - -#if defined(__cplusplus) -extern "C" -{ -#endif /* __cplusplus */ - -#if !defined(HAVE_MODE_T) -typedef unsigned int mode_t; -#endif - - -typedef struct sem_t_ * sem_t; - -PTW32_DLLPORT int __cdecl sem_init (sem_t * sem, - int pshared, - unsigned int value); - -PTW32_DLLPORT int __cdecl sem_destroy (sem_t * sem); - -PTW32_DLLPORT int __cdecl sem_trywait (sem_t * sem); - -PTW32_DLLPORT int __cdecl sem_wait (sem_t * sem); - -PTW32_DLLPORT int __cdecl sem_timedwait (sem_t * sem, - const struct timespec * abstime); - -PTW32_DLLPORT int __cdecl sem_post (sem_t * sem); - -PTW32_DLLPORT int __cdecl sem_post_multiple (sem_t * sem, - int count); - -PTW32_DLLPORT int __cdecl sem_open (const char * name, - int oflag, - mode_t mode, - unsigned int value); - -PTW32_DLLPORT int __cdecl sem_close (sem_t * sem); - -PTW32_DLLPORT int __cdecl sem_unlink (const char * name); - -PTW32_DLLPORT int __cdecl sem_getvalue (sem_t * sem, - int * sval); - -#if defined(__cplusplus) -} /* End of extern "C" */ -#endif /* __cplusplus */ - -#undef PTW32_SEMAPHORE_LEVEL -#undef PTW32_SEMAPHORE_LEVEL_MAX - -#endif /* !SEMAPHORE_H */ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/libpthreadGC2.a b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/libpthreadGC2.a deleted file mode 100644 index 430162364f..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/libpthreadGC2.a and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/pthreadVC2.lib b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/pthreadVC2.lib deleted file mode 100644 index 1b07e0e9aa..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x64/pthreadVC2.lib and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGC2.a b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGC2.a deleted file mode 100644 index df211759f8..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGC2.a and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGCE2.a b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGCE2.a deleted file mode 100644 index 9c56202c58..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/libpthreadGCE2.a and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVC2.lib b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVC2.lib deleted file mode 100644 index c20ee200db..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVC2.lib and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVCE2.lib b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVCE2.lib deleted file mode 100644 index 7f05317ba2..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVCE2.lib and /dev/null differ diff --git a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVSE2.lib b/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVSE2.lib deleted file mode 100644 index 3f3335d469..0000000000 Binary files a/bridge/third_party/quickjs/compat/win32/pthreads/lib/x86/pthreadVSE2.lib and /dev/null differ diff --git a/bridge/third_party/quickjs/include/quickjs/quickjs.h b/bridge/third_party/quickjs/include/quickjs/quickjs.h index 60a3244fe1..f6198145e4 100644 --- a/bridge/third_party/quickjs/include/quickjs/quickjs.h +++ b/bridge/third_party/quickjs/include/quickjs/quickjs.h @@ -554,7 +554,7 @@ static js_force_inline JSValue JS_NewInt64(JSContext *ctx, int64_t val) { if (val == (int32_t)val) { v = JS_NewInt32(ctx, (int32_t) val); } else { - v = __JS_NewFloat64(ctx, val); + v = __JS_NewFloat64(ctx, (double) val); } return v; } diff --git a/bridge/third_party/quickjs/src/core/function.h b/bridge/third_party/quickjs/src/core/function.h index c590a1a3cf..c32070f2f4 100644 --- a/bridge/third_party/quickjs/src/core/function.h +++ b/bridge/third_party/quickjs/src/core/function.h @@ -26,6 +26,10 @@ #ifndef QUICKJS_FUNCTION_H #define QUICKJS_FUNCTION_H +#if _MSC_VER +#include +#endif + #include "quickjs/cutils.h" #include "quickjs/quickjs.h" #include "types.h" diff --git a/bridge/third_party/quickjs/src/libregexp.c b/bridge/third_party/quickjs/src/libregexp.c index 7706b3fe86..c9428721b0 100644 --- a/bridge/third_party/quickjs/src/libregexp.c +++ b/bridge/third_party/quickjs/src/libregexp.c @@ -28,6 +28,10 @@ #include #include +#if _MSC_VER +#include +#endif + #include "quickjs/cutils.h" #include "quickjs/libregexp.h" diff --git a/bridge/webf_bridge.cc b/bridge/webf_bridge.cc index 6f3d297a25..22f95160e1 100644 --- a/bridge/webf_bridge.cc +++ b/bridge/webf_bridge.cc @@ -3,7 +3,6 @@ */ #include "include/webf_bridge.h" -#include "core/api/api.h" #include "core/dart_isolate_context.h" #include "core/html/parser/html_parser.h" #include "core/page.h" @@ -142,8 +141,9 @@ void evaluateScripts(void* page_, auto page = reinterpret_cast(page_); Dart_PersistentHandle persistent_handle = Dart_NewPersistentHandle_DL(dart_handle); page->executingContext()->dartIsolateContext()->dispatcher()->PostToJs( - page->isDedicated(), page->contextId(), webf::evaluateScriptsInternal, page_, code, code_len, parsed_bytecodes, - bytecode_len, bundleFilename, start_line, profile_id, persistent_handle, result_callback); + page->isDedicated(), static_cast(page->contextId()), webf::WebFPage::EvaluateScriptsInternal, page_, + code, code_len, parsed_bytecodes, bytecode_len, bundleFilename, start_line, profile_id, persistent_handle, + result_callback); } void dumpQuickjsByteCode(void* page_, @@ -162,8 +162,8 @@ void dumpQuickjsByteCode(void* page_, auto page = reinterpret_cast(page_); Dart_PersistentHandle persistent_handle = Dart_NewPersistentHandle_DL(dart_handle); page->dartIsolateContext()->dispatcher()->PostToJs( - page->isDedicated(), page->contextId(), webf::dumpQuickJsByteCodeInternal, page, profile_id, code, code_len, - parsed_bytecodes, bytecode_len, url, persistent_handle, result_callback); + page->isDedicated(), static_cast(page->contextId()), webf::WebFPage::DumpQuickJsByteCodeInternal, page, + profile_id, code, code_len, parsed_bytecodes, bytecode_len, url, persistent_handle, result_callback); } void evaluateQuickjsByteCode(void* page_, @@ -177,9 +177,9 @@ void evaluateQuickjsByteCode(void* page_, #endif auto page = reinterpret_cast(page_); Dart_PersistentHandle persistent_handle = Dart_NewPersistentHandle_DL(dart_handle); - page->dartIsolateContext()->dispatcher()->PostToJs(page->isDedicated(), page->contextId(), - webf::evaluateQuickjsByteCodeInternal, page_, bytes, byteLen, - profile_id, persistent_handle, result_callback); + page->dartIsolateContext()->dispatcher()->PostToJs(page->isDedicated(), static_cast(page->contextId()), + webf::WebFPage::EvaluateQuickjsByteCodeInternal, page_, bytes, + byteLen, profile_id, persistent_handle, result_callback); } void parseHTML(void* page_, @@ -194,8 +194,8 @@ void parseHTML(void* page_, auto page = reinterpret_cast(page_); Dart_PersistentHandle persistent_handle = Dart_NewPersistentHandle_DL(dart_handle); page->executingContext()->dartIsolateContext()->dispatcher()->PostToJs( - page->isDedicated(), page->contextId(), webf::parseHTMLInternal, page_, code, length, profile_id, - persistent_handle, result_callback); + page->isDedicated(), static_cast(page->contextId()), webf::WebFPage::ParseHTMLInternal, page_, code, + length, profile_id, persistent_handle, result_callback); } void registerPluginByteCode(uint8_t* bytes, int32_t length, const char* pluginName) { @@ -241,8 +241,9 @@ void invokeModuleEvent(void* page_, auto dart_isolate_context = page->executingContext()->dartIsolateContext(); auto is_dedicated = page->executingContext()->isDedicated(); auto context_id = page->contextId(); - dart_isolate_context->dispatcher()->PostToJs(is_dedicated, context_id, webf::invokeModuleEventInternal, page_, module, - eventType, event, extra, persistent_handle, result_callback); + dart_isolate_context->dispatcher()->PostToJs(is_dedicated, static_cast(context_id), + webf::WebFPage::InvokeModuleEventInternal, page_, module, eventType, + event, extra, persistent_handle, result_callback); } void collectNativeProfileData(void* ptr, const char** data, uint32_t* len) { @@ -251,7 +252,7 @@ void collectNativeProfileData(void* ptr, const char** data, uint32_t* len) { *data = static_cast(webf::dart_malloc(sizeof(char) * result.size() + 1)); memcpy((void*)*data, result.c_str(), sizeof(char) * result.size() + 1); - *len = result.size(); + *len = static_cast(result.size()); } void clearNativeProfileData(void* ptr) { diff --git a/integration_tests/macos/Runner/AppDelegate.swift b/integration_tests/macos/Runner/AppDelegate.swift index d53ef64377..8e02df2888 100644 --- a/integration_tests/macos/Runner/AppDelegate.swift +++ b/integration_tests/macos/Runner/AppDelegate.swift @@ -1,7 +1,7 @@ import Cocoa import FlutterMacOS -@NSApplicationMain +@main class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true diff --git a/integration_tests/webpack.config.js b/integration_tests/webpack.config.js index a6d7a1546c..937c34da60 100644 --- a/integration_tests/webpack.config.js +++ b/integration_tests/webpack.config.js @@ -15,30 +15,29 @@ const specGroup = require('./spec_group.json'); let coreSpecFiles = []; if (process.env.SPEC_SCOPE) { - let targetSpec = specGroup.find((item) => item.name === process.env.SPEC_SCOPE.trim()); - if (targetSpec) { - let targetSpecCollection = targetSpec.specs; - targetSpecCollection.forEach(spec => { - let files = glob.sync(spec, { - cwd: context, - ignore: ['node_modules/**'], - }).map((file) => './' + file); - coreSpecFiles = coreSpecFiles.concat(files); - }); - } else { - throw new Error('Unknown target spec scope: ' + process.env.SPEC_SCOPE); - } + let targetSpec = specGroup.find((item) => item.name === process.env.SPEC_SCOPE.trim()); + if (targetSpec) { + let targetSpecCollection = targetSpec.specs; + targetSpecCollection.forEach(spec => { + let files = glob.sync(spec, { + cwd: context, + ignore: ['node_modules/**'], + }).map((file) => './' + file); + coreSpecFiles = coreSpecFiles.concat(files); + }); + } else { + throw new Error('Unknown target spec scope: ' + process.env.SPEC_SCOPE); + } } else { - coreSpecFiles = glob.sync('specs/**/*.{js,jsx,ts,tsx,html,svg}', { - cwd: context, - ignore: ['node_modules/**'], - }).map((file) => './' + file); - if (process.env.WEBF_TEST_FILTER) { - coreSpecFiles = coreSpecFiles.filter(name => name.includes(process.env.WEBF_TEST_FILTER)) - } + coreSpecFiles = glob.sync('specs/**/*.{js,jsx,ts,tsx,html,svg}', { + cwd: context, + ignore: ['node_modules/**'], + }).map((file) => './' + file); + if (process.env.WEBF_TEST_FILTER) { + coreSpecFiles = coreSpecFiles.filter(name => name.includes(process.env.WEBF_TEST_FILTER)) + } } - const dartVersion = execSync('dart --version', {encoding: 'utf-8'}); const regExp = /Dart SDK version: (\d\.\d{1,3}\.\d{1,3}) /; let versionNum = regExp.exec(dartVersion)[1]; diff --git a/package.json b/package.json index 546058cd72..351b9228ec 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "build:bridge:all": "node scripts/prepare_webf_release_binary", "build:bridge:all:release": "WEBF_BUILD=Release node scripts/prepare_webf_release_binary", "build_bridge:all:profile": "ENABLE_PROFILE=true npm run build:bridge:all:release", + "generate_binding_code": "node scripts/generate_binding_code", "build:clean": "node scripts/clean.js", "pretest": "npm install && node scripts/build_darwin_dylib", "posttest": "npm run lint", diff --git a/scripts/generate_binding_code.js b/scripts/generate_binding_code.js index f70c0242d9..22985eea43 100644 --- a/scripts/generate_binding_code.js +++ b/scripts/generate_binding_code.js @@ -8,6 +8,7 @@ require('./tasks'); // Run tasks series( + 'compile-polyfill', 'generate-bindings-code', )((err) => { if (err) { diff --git a/scripts/tasks.js b/scripts/tasks.js index 7b9d6a66b6..01771831be 100644 --- a/scripts/tasks.js +++ b/scripts/tasks.js @@ -542,7 +542,7 @@ task('generate-bindings-code', (done) => { if (!fs.existsSync(path.join(paths.codeGen, 'node_modules'))) { spawnSync(NPM, ['install'], { cwd: paths.codeGen, - stdio: 'inherit' + stdio: 'inherit' }); } @@ -551,6 +551,7 @@ task('generate-bindings-code', (done) => { env: { ...process.env, }, + shell: true, stdio: 'inherit' }); @@ -563,6 +564,7 @@ task('generate-bindings-code', (done) => { env: { ...process.env, }, + shell: true, stdio: 'inherit' }); @@ -589,7 +591,7 @@ task('build-window-webf-lib', (done) => { const soBinaryDirectory = path.join(paths.bridge, `build/windows/lib/`); const bridgeCmakeDir = path.join(paths.bridge, 'cmake-build-windows'); // generate project - execSync(`cmake --log-level=VERBOSE -DCMAKE_BUILD_TYPE=${buildType} ${externCmakeArgs.join(' ')} -DVERBOSE_CONFIGURE=ON -B ${bridgeCmakeDir} -S ${paths.bridge}`, + execSync(`cmake -DCMAKE_BUILD_TYPE=${buildType} ${externCmakeArgs.join(' ')} -B ${bridgeCmakeDir} -S ${paths.bridge}`, { cwd: paths.bridge, stdio: 'inherit', diff --git a/webf/android/build.gradle b/webf/android/build.gradle index 98b660c5e4..d1342b23b0 100644 --- a/webf/android/build.gradle +++ b/webf/android/build.gradle @@ -3,62 +3,65 @@ version '1.0' buildscript { repositories { - maven { - url 'https://maven.aliyun.com/repository/public/' - } - maven { - url 'https://maven.aliyun.com/repository/google/' - } - maven { - url 'https://maven.aliyun.com/repository/jcenter/' - } + google() + mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:4.1.0' + classpath("com.android.tools.build:gradle:7.3.0") } } -rootProject.allprojects { + +allprojects { repositories { - maven { - url 'https://maven.aliyun.com/repository/public/' - } - maven { - url 'https://maven.aliyun.com/repository/google/' - } - maven { - url 'https://maven.aliyun.com/repository/jcenter/' - } + google() + mavenCentral() } } apply plugin: 'com.android.library' + android { - compileSdkVersion 29 + if (project.android.hasProperty("namespace")) { + namespace = "com.openwebf.webf" + } - defaultConfig { - minSdkVersion 16 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + compileSdk = 34 - ndk { - abiFilters 'armeabi-v7a', 'arm64-v8a' - } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + defaultConfig { + minSdk = 21 externalNativeBuild { cmake { - abiFilters 'armeabi-v7a', 'arm64-v8a' + arguments "-DANDROID_STL=c++_shared", "-DIS_ANDROID=TRUE" } } } - lintOptions { - disable 'InvalidPackage' - } - sourceSets { - main { - jniLibs.srcDirs = ['jniLibs'] + // Use the NDK version + ndkVersion = "22.1.7171670" + + // Invoke the shared CMake build with the Android Gradle Plugin. + externalNativeBuild { + cmake { + path = "../src/CMakeLists.txt" + // The default CMake version for the Android Gradle Plugin is 3.10.2. + // https://developer.android.com/studio/projects/install-ndk#vanilla_cmake + // + // The Flutter tooling requires that developers have CMake 3.10 or later + // installed. You should not increase this version, as doing so will cause + // the plugin to fail to compile for some customers of the plugin. + // version "3.10.2" } } + + lintOptions { + disable 'InvalidPackage' + } } diff --git a/webf/android/jniLibs/arm64-v8a/libc++_shared.so b/webf/android/jniLibs/arm64-v8a/libc++_shared.so deleted file mode 120000 index 32812e6de1..0000000000 --- a/webf/android/jniLibs/arm64-v8a/libc++_shared.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/arm64-v8a/libc++_shared.so \ No newline at end of file diff --git a/webf/android/jniLibs/arm64-v8a/libquickjs.so b/webf/android/jniLibs/arm64-v8a/libquickjs.so deleted file mode 120000 index 9991c5f376..0000000000 --- a/webf/android/jniLibs/arm64-v8a/libquickjs.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/arm64-v8a/libquickjs.so \ No newline at end of file diff --git a/webf/android/jniLibs/arm64-v8a/libwebf.so b/webf/android/jniLibs/arm64-v8a/libwebf.so deleted file mode 120000 index 3f24cbcd80..0000000000 --- a/webf/android/jniLibs/arm64-v8a/libwebf.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/arm64-v8a/libwebf.so \ No newline at end of file diff --git a/webf/android/jniLibs/armeabi-v7a/libc++_shared.so b/webf/android/jniLibs/armeabi-v7a/libc++_shared.so deleted file mode 120000 index acf0703444..0000000000 --- a/webf/android/jniLibs/armeabi-v7a/libc++_shared.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/armeabi-v7a/libc++_shared.so \ No newline at end of file diff --git a/webf/android/jniLibs/armeabi-v7a/libquickjs.so b/webf/android/jniLibs/armeabi-v7a/libquickjs.so deleted file mode 120000 index 604b3fdad2..0000000000 --- a/webf/android/jniLibs/armeabi-v7a/libquickjs.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/armeabi-v7a/libquickjs.so \ No newline at end of file diff --git a/webf/android/jniLibs/armeabi-v7a/libwebf.so b/webf/android/jniLibs/armeabi-v7a/libwebf.so deleted file mode 120000 index bb2435fab6..0000000000 --- a/webf/android/jniLibs/armeabi-v7a/libwebf.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/armeabi-v7a/libwebf.so \ No newline at end of file diff --git a/webf/android/jniLibs/x86/libc++_shared.so b/webf/android/jniLibs/x86/libc++_shared.so deleted file mode 120000 index f541ad7f39..0000000000 --- a/webf/android/jniLibs/x86/libc++_shared.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/x86/libc++_shared.so \ No newline at end of file diff --git a/webf/android/jniLibs/x86/libquickjs.so b/webf/android/jniLibs/x86/libquickjs.so deleted file mode 120000 index a7e4f03071..0000000000 --- a/webf/android/jniLibs/x86/libquickjs.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/x86/libquickjs.so \ No newline at end of file diff --git a/webf/android/jniLibs/x86/libwebf.so b/webf/android/jniLibs/x86/libwebf.so deleted file mode 120000 index 1513bec19f..0000000000 --- a/webf/android/jniLibs/x86/libwebf.so +++ /dev/null @@ -1 +0,0 @@ -../../../../bridge/build/android/lib/x86/libwebf.so \ No newline at end of file diff --git a/webf/example/android/.gitignore b/webf/example/android/.gitignore index 6f568019d3..55afd919c6 100644 --- a/webf/example/android/.gitignore +++ b/webf/example/android/.gitignore @@ -7,7 +7,7 @@ gradle-wrapper.jar GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. -# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +# See https://flutter.dev/to/reference-keystore key.properties **/*.keystore **/*.jks diff --git a/webf/example/android/app/build.gradle b/webf/example/android/app/build.gradle index 5ab6fc21b0..6a5769bbb0 100644 --- a/webf/example/android/app/build.gradle +++ b/webf/example/android/app/build.gradle @@ -1,57 +1,45 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' +plugins { + id "com.android.application" + id "kotlin-android" + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id "dev.flutter.flutter-gradle-plugin" } -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply plugin: 'kotlin-android' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - android { - compileSdkVersion flutter.compileSdkVersion - ndkVersion flutter.ndkVersion + namespace = "com.example.app" + compileSdk = flutter.compileSdkVersion + compileSdkVersion = 34 + ndkVersion = flutter.ndkVersion compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8 } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.openwebf.webf_example" - minSdkVersion flutter.minSdkVersion - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName + applicationId = "com.example.app" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug + signingConfig = signingConfigs.debug } } } flutter { - source '../..' + source = "../.." } diff --git a/webf/example/android/app/src/debug/AndroidManifest.xml b/webf/example/android/app/src/debug/AndroidManifest.xml index caa5f72cfb..399f6981d5 100644 --- a/webf/example/android/app/src/debug/AndroidManifest.xml +++ b/webf/example/android/app/src/debug/AndroidManifest.xml @@ -1,6 +1,6 @@ - - diff --git a/webf/example/android/app/src/main/AndroidManifest.xml b/webf/example/android/app/src/main/AndroidManifest.xml index 0bae586864..6ee3df00cf 100644 --- a/webf/example/android/app/src/main/AndroidManifest.xml +++ b/webf/example/android/app/src/main/AndroidManifest.xml @@ -1,13 +1,5 @@ - - - - - + @@ -15,6 +7,7 @@ android:name=".MainActivity" android:exported="true" android:launchMode="singleTop" + android:taskAffinity="" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" @@ -27,15 +20,6 @@ android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme" /> - - @@ -47,4 +31,15 @@ android:name="flutterEmbedding" android:value="2" /> + + + + + + + diff --git a/webf/example/android/app/src/main/java/com/openwebf/webf_example/MainActivity.java b/webf/example/android/app/src/main/java/com/openwebf/webf_example/MainActivity.java deleted file mode 100644 index f1fae10e24..0000000000 --- a/webf/example/android/app/src/main/java/com/openwebf/webf_example/MainActivity.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.openwebf.webf_example; - -import io.flutter.embedding.android.FlutterActivity; - -public class MainActivity extends FlutterActivity { -} diff --git a/webf/example/android/app/src/main/kotlin/com/example/app/MainActivity.kt b/webf/example/android/app/src/main/kotlin/com/example/app/MainActivity.kt new file mode 100644 index 0000000000..026d9a938b --- /dev/null +++ b/webf/example/android/app/src/main/kotlin/com/example/app/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.app + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() diff --git a/webf/example/android/app/src/main/res/drawable-v21/launch_background.xml b/webf/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000000..f74085f3f6 --- /dev/null +++ b/webf/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/webf/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/webf/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png index d840144b24..db77bb4b7b 100644 Binary files a/webf/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and b/webf/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/webf/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/webf/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png index 6d8e30ae73..17987b79bb 100644 Binary files a/webf/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and b/webf/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/webf/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/webf/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png index c92670f5da..09d4391482 100644 Binary files a/webf/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and b/webf/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/webf/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/webf/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png index 9fa02240e9..d5f1c8d34e 100644 Binary files a/webf/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and b/webf/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/webf/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/webf/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png index b8ac239e22..4d6372eebd 100644 Binary files a/webf/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and b/webf/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/webf/example/android/app/src/main/res/values-night/styles.xml b/webf/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000000..06952be745 --- /dev/null +++ b/webf/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/webf/example/android/app/src/main/res/values/styles.xml b/webf/example/android/app/src/main/res/values/styles.xml index 322503e4c6..cb1ef88056 100644 --- a/webf/example/android/app/src/main/res/values/styles.xml +++ b/webf/example/android/app/src/main/res/values/styles.xml @@ -1,9 +1,9 @@ - - - diff --git a/webf/example/android/app/src/profile/AndroidManifest.xml b/webf/example/android/app/src/profile/AndroidManifest.xml index caa5f72cfb..399f6981d5 100644 --- a/webf/example/android/app/src/profile/AndroidManifest.xml +++ b/webf/example/android/app/src/profile/AndroidManifest.xml @@ -1,6 +1,6 @@ - - diff --git a/webf/example/android/build.gradle b/webf/example/android/build.gradle index 3cdaac9588..d2ffbffa4c 100644 --- a/webf/example/android/build.gradle +++ b/webf/example/android/build.gradle @@ -1,16 +1,3 @@ -buildscript { - ext.kotlin_version = '1.6.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:7.1.2' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - allprojects { repositories { google() @@ -18,12 +5,12 @@ allprojects { } } -rootProject.buildDir = '../build' +rootProject.buildDir = "../build" subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { - project.evaluationDependsOn(':app') + project.evaluationDependsOn(":app") } tasks.register("clean", Delete) { diff --git a/webf/example/android/gradle.properties b/webf/example/android/gradle.properties index 94adc3a3f9..2597170821 100644 --- a/webf/example/android/gradle.properties +++ b/webf/example/android/gradle.properties @@ -1,3 +1,3 @@ -org.gradle.jvmargs=-Xmx1536M +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true diff --git a/webf/example/android/gradle/wrapper/gradle-wrapper.properties b/webf/example/android/gradle/wrapper/gradle-wrapper.properties index cb24abda10..e1ca574ef0 100644 --- a/webf/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/webf/example/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip diff --git a/webf/example/android/settings.gradle b/webf/example/android/settings.gradle index 44e62bcf06..536165d35a 100644 --- a/webf/example/android/settings.gradle +++ b/webf/example/android/settings.gradle @@ -1,11 +1,25 @@ -include ':app' +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() -def localPropertiesFile = new File(rootProject.projectDir, "local.properties") -def properties = new Properties() + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") -assert localPropertiesFile.exists() -localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} -def flutterSdkPath = properties.getProperty("flutter.sdk") -assert flutterSdkPath != null, "flutter.sdk not set in local.properties" -apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "7.3.0" apply false + id "org.jetbrains.kotlin.android" version "1.7.10" apply false +} + +include ":app" diff --git a/webf/example/assets/bundle.html b/webf/example/assets/bundle.html index 431559ebb8..a67b970712 100644 --- a/webf/example/assets/bundle.html +++ b/webf/example/assets/bundle.html @@ -44,7 +44,7 @@ diff --git a/webf/example/ios/Runner.xcodeproj/project.pbxproj b/webf/example/ios/Runner.xcodeproj/project.pbxproj index 9673f48f22..1769ead327 100644 --- a/webf/example/ios/Runner.xcodeproj/project.pbxproj +++ b/webf/example/ios/Runner.xcodeproj/project.pbxproj @@ -373,7 +373,7 @@ "$(inherited)", "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.krakenExample; + PRODUCT_BUNDLE_IDENTIFIER = com.openwebf.example; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -511,7 +511,7 @@ "$(inherited)", "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.krakenExample; + PRODUCT_BUNDLE_IDENTIFIER = com.openwebf.example; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -544,7 +544,7 @@ "$(inherited)", "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.openkraken.krakenExample; + PRODUCT_BUNDLE_IDENTIFIER = com.openwebf.example; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/webf/example/ios/Runner/Info.plist b/webf/example/ios/Runner/Info.plist index da544ce862..858602aaa7 100644 --- a/webf/example/ios/Runner/Info.plist +++ b/webf/example/ios/Runner/Info.plist @@ -2,6 +2,8 @@ + CADisableMinimumFrameDurationOnPhone + CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable @@ -22,6 +24,8 @@ $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS + UIApplicationSupportsIndirectInputEvents + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile @@ -41,9 +45,5 @@ UIViewControllerBasedStatusBarAppearance - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - diff --git a/webf/example/lib/main.dart b/webf/example/lib/main.dart index dc3bd452ea..c5ee3622b7 100644 --- a/webf/example/lib/main.dart +++ b/webf/example/lib/main.dart @@ -42,6 +42,7 @@ class FirstPageState extends State { super.didChangeDependencies(); controller = WebFController( context, + runningThread: FlutterUIThread(), devToolsService: ChromeDevToolsService(), ); controller.preload(WebFBundle.fromUrl('assets:assets/bundle.html')); diff --git a/webf/example/linux/flutter/generated_plugins.cmake b/webf/example/linux/flutter/generated_plugins.cmake index 3b18a0b7de..c260b00e02 100644 --- a/webf/example/linux/flutter/generated_plugins.cmake +++ b/webf/example/linux/flutter/generated_plugins.cmake @@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + example_app ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/webf/example/macos/Runner.xcodeproj/project.pbxproj b/webf/example/macos/Runner.xcodeproj/project.pbxproj index 664b1d536f..8dcf087593 100644 --- a/webf/example/macos/Runner.xcodeproj/project.pbxproj +++ b/webf/example/macos/Runner.xcodeproj/project.pbxproj @@ -202,7 +202,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1430; + LastUpgradeCheck = 1510; ORGANIZATIONNAME = "The Flutter Authors"; TargetAttributes = { 33CC10EC2044A3C60003C045 = { @@ -260,14 +260,14 @@ ); inputPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/shared_preferences_foundation/shared_preferences_foundation.framework", + "${BUILT_PRODUCTS_DIR}/example_app/example_app.framework", "${PODS_ROOT}/../Flutter/ephemeral/.symlinks/plugins/webf/macos/libwebf.dylib", "${PODS_ROOT}/../Flutter/ephemeral/.symlinks/plugins/webf/macos/libquickjs.dylib", "${BUILT_PRODUCTS_DIR}/webf/webf.framework", ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/shared_preferences_foundation.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/example_app.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libwebf.dylib", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/libquickjs.dylib", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/webf.framework", diff --git a/webf/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/webf/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index aae12fcb81..5721ea5474 100644 --- a/webf/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/webf/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ + diff --git a/webf/example/rust_builder/cargokit/.github/workflows/check_and_lint.yml b/webf/example/rust_builder/cargokit/.github/workflows/check_and_lint.yml new file mode 100644 index 0000000000..adec80e1a2 --- /dev/null +++ b/webf/example/rust_builder/cargokit/.github/workflows/check_and_lint.yml @@ -0,0 +1,26 @@ +on: + pull_request: + push: + branches: + - main + +name: Check and Lint + +jobs: + Flutter: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ee0669bd1cc54295c223e0bb666b733df41de1c5 #v2.7.0 + - uses: dart-lang/setup-dart@b64355ae6ca0b5d484f0106a033dd1388965d06d #1.6.0 + - name: Pub Get + run: dart pub get --no-precompile + working-directory: build_tool + - name: Dart Format + run: dart format . --output=none --set-exit-if-changed + working-directory: build_tool + - name: Analyze + run: dart analyze + working-directory: build_tool + - name: Test + run: dart test + working-directory: build_tool diff --git a/webf/example/rust_builder/cargokit/.github/workflows/test_example_plugin_build.yml b/webf/example/rust_builder/cargokit/.github/workflows/test_example_plugin_build.yml new file mode 100644 index 0000000000..4fb0252dc1 --- /dev/null +++ b/webf/example/rust_builder/cargokit/.github/workflows/test_example_plugin_build.yml @@ -0,0 +1,86 @@ +on: + pull_request: + push: + branches: + - main + +name: Test Example Plugin + +jobs: + Build: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - macOS-latest + - windows-latest + build_mode: + - debug + - profile + - release + env: + EXAMPLE_DIR: "a b/hello_rust_ffi_plugin/example" + CARGOKIT_VERBOSE: 1 + steps: + - name: Extract branch name + shell: bash + run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT + id: extract_branch + - name: Setup Repository + shell: bash + run: | + mkdir "a b" # Space is intentional + cd "a b" + git config --global user.email "you@example.com" + git config --global user.name "Your Name" + # "advanced" branch has extra iOS flavor and uses rust nightly for release builds + git clone -b advanced https://github.com/irondash/hello_rust_ffi_plugin + cd hello_rust_ffi_plugin + git subtree pull --prefix cargokit https://github.com/${{ github.event.pull_request.head.repo.full_name || github.repository }} ${{ steps.extract_branch.outputs.branch }} --squash + - uses: subosito/flutter-action@cc97e1648fff6ca5cc647fa67f47e70f7895510b # 2.11.0 + with: + channel: "stable" + - name: Install GTK + if: (matrix.os == 'ubuntu-latest') + run: sudo apt-get update && sudo apt-get install libgtk-3-dev + - name: Install ninja-build + if: (matrix.os == 'ubuntu-latest') + run: sudo apt-get update && sudo apt-get install ninja-build + - name: Build Linux (${{ matrix.build_mode }}) + if: matrix.os == 'ubuntu-latest' + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: flutter build linux --${{ matrix.build_mode }} -v + - name: Build macOS (${{ matrix.build_mode }}) + if: matrix.os == 'macos-latest' + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: flutter build macos --${{ matrix.build_mode }} -v + - name: Build iOS (${{ matrix.build_mode }}) + if: matrix.os == 'macos-latest' + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: flutter build ios --${{ matrix.build_mode }} --no-codesign -v + - name: Build iOS (${{ matrix.build_mode }}) - flavor1 + if: matrix.os == 'macos-latest' + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: flutter build ios --flavor flavor1 --${{ matrix.build_mode }} --no-codesign -v + - name: Build Windows (${{ matrix.build_mode }}) + if: matrix.os == 'windows-latest' + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: flutter build windows --${{ matrix.build_mode }} -v + - name: Build Android (${{ matrix.build_mode }}) + shell: bash + working-directory: ${{ env.EXAMPLE_DIR }} + run: | + if [[ $(sysctl hw.optional.arm64) == *"hw.optional.arm64: 1"* ]]; then + export JAVA_HOME=$JAVA_HOME_17_arm64 + else + export JAVA_HOME=$JAVA_HOME_11_X64 + fi + flutter build apk --${{ matrix.build_mode }} -v + diff --git a/webf/example/rust_builder/cargokit/.gitignore b/webf/example/rust_builder/cargokit/.gitignore new file mode 100644 index 0000000000..cf7bb868c0 --- /dev/null +++ b/webf/example/rust_builder/cargokit/.gitignore @@ -0,0 +1,4 @@ +target +.dart_tool +*.iml +!pubspec.lock diff --git a/webf/example/rust_builder/cargokit/LICENSE b/webf/example/rust_builder/cargokit/LICENSE new file mode 100644 index 0000000000..54a7d58935 --- /dev/null +++ b/webf/example/rust_builder/cargokit/LICENSE @@ -0,0 +1,39 @@ +Copyright 2022 Matej Knopp + +================================================================================ + +MIT LICENSE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================================================================================ + +APACHE LICENSE, VERSION 2.0 + +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. + diff --git a/webf/example/rust_builder/cargokit/README b/webf/example/rust_builder/cargokit/README new file mode 100644 index 0000000000..8ae4a073e7 --- /dev/null +++ b/webf/example/rust_builder/cargokit/README @@ -0,0 +1,8 @@ +Experimental repository to provide glue for seamlessly integrating cargo build +with flutter plugins and packages. + +See https://matejknopp.com/post/flutter_plugin_in_rust_with_no_prebuilt_binaries/ +for a tutorial on how to use Cargokit. + +Example plugin available at https://github.com/irondash/hello_rust_ffi_plugin. + diff --git a/webf/example/rust_builder/cargokit/build_pod.sh b/webf/example/rust_builder/cargokit/build_pod.sh new file mode 100755 index 0000000000..ed0e0d987d --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_pod.sh @@ -0,0 +1,58 @@ +#!/bin/sh +set -e + +BASEDIR=$(dirname "$0") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +BASEDIR=$(cd "$BASEDIR" ; pwd -P) + +# Remove XCode SDK from path. Otherwise this breaks tool compilation when building iOS project +NEW_PATH=`echo $PATH | tr ":" "\n" | grep -v "Contents/Developer/" | tr "\n" ":"` + +export PATH=${NEW_PATH%?} # remove trailing : + +env + +# Platform name (macosx, iphoneos, iphonesimulator) +export CARGOKIT_DARWIN_PLATFORM_NAME=$PLATFORM_NAME + +# Arctive architectures (arm64, armv7, x86_64), space separated. +export CARGOKIT_DARWIN_ARCHS=$ARCHS + +# Current build configuration (Debug, Release) +export CARGOKIT_CONFIGURATION=$CONFIGURATION + +# Path to directory containing Cargo.toml. +export CARGOKIT_MANIFEST_DIR=$PODS_TARGET_SRCROOT/$1 + +# Temporary directory for build artifacts. +export CARGOKIT_TARGET_TEMP_DIR=$TARGET_TEMP_DIR + +# Output directory for final artifacts. +export CARGOKIT_OUTPUT_DIR=$PODS_CONFIGURATION_BUILD_DIR/$PRODUCT_NAME + +# Directory to store built tool artifacts. +export CARGOKIT_TOOL_TEMP_DIR=$TARGET_TEMP_DIR/build_tool + +# Directory inside root project. Not necessarily the top level directory of root project. +export CARGOKIT_ROOT_PROJECT_DIR=$SRCROOT + +FLUTTER_EXPORT_BUILD_ENVIRONMENT=( + "$PODS_ROOT/../Flutter/ephemeral/flutter_export_environment.sh" # macOS + "$PODS_ROOT/../Flutter/flutter_export_environment.sh" # iOS +) + +for path in "${FLUTTER_EXPORT_BUILD_ENVIRONMENT[@]}" +do + if [[ -f "$path" ]]; then + source "$path" + fi +done + +sh "$BASEDIR/run_build_tool.sh" build-pod "$@" + +# Make a symlink from built framework to phony file, which will be used as input to +# build script. This should force rebuild (podspec currently doesn't support alwaysOutOfDate +# attribute on custom build phase) +ln -fs "$OBJROOT/XCBuildData/build.db" "${BUILT_PRODUCTS_DIR}/cargokit_phony" +ln -fs "${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}" "${BUILT_PRODUCTS_DIR}/cargokit_phony_out" diff --git a/webf/example/rust_builder/cargokit/build_tool/README.md b/webf/example/rust_builder/cargokit/build_tool/README.md new file mode 100644 index 0000000000..3816eca3ad --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/README.md @@ -0,0 +1,2 @@ +A sample command-line application with an entrypoint in `bin/`, library code +in `lib/`, and example unit test in `test/`. diff --git a/webf/example/rust_builder/cargokit/build_tool/analysis_options.yaml b/webf/example/rust_builder/cargokit/build_tool/analysis_options.yaml new file mode 100644 index 0000000000..a1aad5b3da --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/analysis_options.yaml @@ -0,0 +1,31 @@ +# This file configures the static analysis results for your project (errors, +# warnings, and lints). +# +# This enables the 'recommended' set of lints from `package:lints`. +# This set helps identify many issues that may lead to problems when running +# or consuming Dart code, and enforces writing Dart using a single, idiomatic +# style and format. +# +# If you want a smaller set of lints you can change this to specify +# 'package:lints/core.yaml'. These are just the most critical lints +# (the recommended set includes the core lints). +# The core lints are also what is used by pub.dev for scoring packages. + +include: package:lints/recommended.yaml + +# Uncomment the following section to specify additional rules. + +linter: + rules: + - prefer_relative_imports + - directives_ordering + +# analyzer: +# exclude: +# - path/to/excluded/files/** + +# For more information about the core and recommended set of lints, see +# https://dart.dev/go/core-lints + +# For additional information about configuring this file, see +# https://dart.dev/guides/language/analysis-options diff --git a/webf/example/rust_builder/cargokit/build_tool/bin/build_tool.dart b/webf/example/rust_builder/cargokit/build_tool/bin/build_tool.dart new file mode 100644 index 0000000000..f27ec75c3b --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/bin/build_tool.dart @@ -0,0 +1,5 @@ +import 'package:build_tool/build_tool.dart' as build_tool; + +void main(List arguments) { + build_tool.runMain(arguments); +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/build_tool.dart b/webf/example/rust_builder/cargokit/build_tool/lib/build_tool.dart new file mode 100644 index 0000000000..b329c01a37 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/build_tool.dart @@ -0,0 +1,5 @@ +import 'src/build_tool.dart' as build_tool; + +Future runMain(List args) async { + return build_tool.runMain(args); +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/android_environment.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/android_environment.dart new file mode 100644 index 0000000000..9342964b69 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/android_environment.dart @@ -0,0 +1,192 @@ +import 'dart:io'; +import 'dart:isolate'; +import 'dart:math' as math; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; +import 'package:version/version.dart'; + +import 'target.dart'; +import 'util.dart'; + +class AndroidEnvironment { + AndroidEnvironment({ + required this.sdkPath, + required this.ndkVersion, + required this.minSdkVersion, + required this.targetTempDir, + required this.target, + }); + + static void clangLinkerWrapper(List args) { + final clang = Platform.environment['_CARGOKIT_NDK_LINK_CLANG']; + if (clang == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_CLANG env var"); + } + final target = Platform.environment['_CARGOKIT_NDK_LINK_TARGET']; + if (target == null) { + throw Exception( + "cargo-ndk rustc linker: didn't find _CARGOKIT_NDK_LINK_TARGET env var"); + } + + runCommand(clang, [ + target, + ...args, + ]); + } + + /// Full path to Android SDK. + final String sdkPath; + + /// Full version of Android NDK. + final String ndkVersion; + + /// Minimum supported SDK version. + final int minSdkVersion; + + /// Target directory for build artifacts. + final String targetTempDir; + + /// Target being built. + final Target target; + + bool ndkIsInstalled() { + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final ndkPackageXml = File(path.join(ndkPath, 'package.xml')); + return ndkPackageXml.existsSync(); + } + + void installNdk({ + required String javaHome, + }) { + final sdkManagerExtension = Platform.isWindows ? '.bat' : ''; + final sdkManager = path.join( + sdkPath, + 'cmdline-tools', + 'latest', + 'bin', + 'sdkmanager$sdkManagerExtension', + ); + + log.info('Installing NDK $ndkVersion'); + runCommand(sdkManager, [ + '--install', + 'ndk;$ndkVersion', + ], environment: { + 'JAVA_HOME': javaHome, + }); + } + + Future> buildEnvironment() async { + final hostArch = Platform.isMacOS + ? "darwin-x86_64" + : (Platform.isLinux ? "linux-x86_64" : "windows-x86_64"); + + final ndkPath = path.join(sdkPath, 'ndk', ndkVersion); + final toolchainPath = path.join( + ndkPath, + 'toolchains', + 'llvm', + 'prebuilt', + hostArch, + 'bin', + ); + + final minSdkVersion = + math.max(target.androidMinSdkVersion!, this.minSdkVersion); + + final exe = Platform.isWindows ? '.exe' : ''; + + final arKey = 'AR_${target.rust}'; + final arValue = ['${target.rust}-ar', 'llvm-ar', 'llvm-ar.exe'] + .map((e) => path.join(toolchainPath, e)) + .firstWhereOrNull((element) => File(element).existsSync()); + if (arValue == null) { + throw Exception('Failed to find ar for $target in $toolchainPath'); + } + + final targetArg = '--target=${target.rust}$minSdkVersion'; + + final ccKey = 'CC_${target.rust}'; + final ccValue = path.join(toolchainPath, 'clang$exe'); + final cfFlagsKey = 'CFLAGS_${target.rust}'; + final cFlagsValue = targetArg; + + final cxxKey = 'CXX_${target.rust}'; + final cxxValue = path.join(toolchainPath, 'clang++$exe'); + final cxxFlagsKey = 'CXXFLAGS_${target.rust}'; + final cxxFlagsValue = targetArg; + + final linkerKey = + 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'.toUpperCase(); + + final ranlibKey = 'RANLIB_${target.rust}'; + final ranlibValue = path.join(toolchainPath, 'llvm-ranlib$exe'); + + final ndkVersionParsed = Version.parse(ndkVersion); + final rustFlagsKey = 'CARGO_ENCODED_RUSTFLAGS'; + final rustFlagsValue = _libGccWorkaround(targetTempDir, ndkVersionParsed); + + final runRustTool = + Platform.isWindows ? 'run_build_tool.cmd' : 'run_build_tool.sh'; + + final packagePath = (await Isolate.resolvePackageUri( + Uri.parse('package:build_tool/buildtool.dart')))! + .toFilePath(); + final selfPath = path.canonicalize(path.join( + packagePath, + '..', + '..', + '..', + runRustTool, + )); + + // Make sure that run_build_tool is working properly even initially launched directly + // through dart run. + final toolTempDir = + Platform.environment['CARGOKIT_TOOL_TEMP_DIR'] ?? targetTempDir; + + return { + arKey: arValue, + ccKey: ccValue, + cfFlagsKey: cFlagsValue, + cxxKey: cxxValue, + cxxFlagsKey: cxxFlagsValue, + ranlibKey: ranlibValue, + rustFlagsKey: rustFlagsValue, + linkerKey: selfPath, + // Recognized by main() so we know when we're acting as a wrapper + '_CARGOKIT_NDK_LINK_TARGET': targetArg, + '_CARGOKIT_NDK_LINK_CLANG': ccValue, + 'CARGOKIT_TOOL_TEMP_DIR': toolTempDir, + }; + } + + // Workaround for libgcc missing in NDK23, inspired by cargo-ndk + String _libGccWorkaround(String buildDir, Version ndkVersion) { + final workaroundDir = path.join( + buildDir, + 'cargokit', + 'libgcc_workaround', + '${ndkVersion.major}', + ); + Directory(workaroundDir).createSync(recursive: true); + if (ndkVersion.major >= 23) { + File(path.join(workaroundDir, 'libgcc.a')) + .writeAsStringSync('INPUT(-lunwind)'); + } else { + // Other way around, untested, forward libgcc.a from libunwind once Rust + // gets updated for NDK23+. + File(path.join(workaroundDir, 'libunwind.a')) + .writeAsStringSync('INPUT(-lgcc)'); + } + + var rustFlags = Platform.environment['CARGO_ENCODED_RUSTFLAGS'] ?? ''; + if (rustFlags.isNotEmpty) { + rustFlags = '$rustFlags\x1f'; + } + rustFlags = '$rustFlags-L\x1f$workaroundDir'; + return rustFlags; + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart new file mode 100644 index 0000000000..ef655a9ef9 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/artifacts_provider.dart @@ -0,0 +1,263 @@ +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'builder.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'rustup.dart'; +import 'target.dart'; + +class Artifact { + /// File system location of the artifact. + final String path; + + /// Actual file name that the artifact should have in destination folder. + final String finalFileName; + + AritifactType get type { + if (finalFileName.endsWith('.dll') || + finalFileName.endsWith('.dll.lib') || + finalFileName.endsWith('.pdb') || + finalFileName.endsWith('.so') || + finalFileName.endsWith('.dylib')) { + return AritifactType.dylib; + } else if (finalFileName.endsWith('.lib') || finalFileName.endsWith('.a')) { + return AritifactType.staticlib; + } else { + throw Exception('Unknown artifact type for $finalFileName'); + } + } + + Artifact({ + required this.path, + required this.finalFileName, + }); +} + +final _log = Logger('artifacts_provider'); + +class ArtifactProvider { + ArtifactProvider({ + required this.environment, + required this.userOptions, + }); + + final BuildEnvironment environment; + final CargokitUserOptions userOptions; + + Future>> getArtifacts(List targets) async { + final result = await _getPrecompiledArtifacts(targets); + + final pendingTargets = List.of(targets); + pendingTargets.removeWhere((element) => result.containsKey(element)); + + if (pendingTargets.isEmpty) { + return result; + } + + final rustup = Rustup(); + for (final target in targets) { + final builder = RustBuilder(target: target, environment: environment); + builder.prepare(rustup); + _log.info('Building ${environment.crateInfo.packageName} for $target'); + final targetDir = await builder.build(); + // For local build accept both static and dynamic libraries. + final artifactNames = { + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + aritifactType: AritifactType.dylib, + remote: false, + ), + ...getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + aritifactType: AritifactType.staticlib, + remote: false, + ) + }; + final artifacts = artifactNames + .map((artifactName) => Artifact( + path: path.join(targetDir, artifactName), + finalFileName: artifactName, + )) + .where((element) => File(element.path).existsSync()) + .toList(); + result[target] = artifacts; + } + return result; + } + + Future>> _getPrecompiledArtifacts( + List targets) async { + if (userOptions.usePrecompiledBinaries == false) { + _log.info('Precompiled binaries are disabled'); + return {}; + } + if (environment.crateOptions.precompiledBinaries == null) { + _log.fine('Precompiled binaries not enabled for this crate'); + return {}; + } + + final start = Stopwatch()..start(); + final crateHash = CrateHash.compute(environment.manifestDir, + tempStorage: environment.targetTempDir); + _log.fine( + 'Computed crate hash $crateHash in ${start.elapsedMilliseconds}ms'); + + final downloadedArtifactsDir = + path.join(environment.targetTempDir, 'precompiled', crateHash); + Directory(downloadedArtifactsDir).createSync(recursive: true); + + final res = >{}; + + for (final target in targets) { + final requiredArtifacts = getArtifactNames( + target: target, + libraryName: environment.crateInfo.packageName, + remote: true, + ); + final artifactsForTarget = []; + + for (final artifact in requiredArtifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final downloadedPath = path.join(downloadedArtifactsDir, fileName); + if (!File(downloadedPath).existsSync()) { + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + await _tryDownloadArtifacts( + crateHash: crateHash, + fileName: fileName, + signatureFileName: signatureFileName, + finalPath: downloadedPath, + ); + } + if (File(downloadedPath).existsSync()) { + artifactsForTarget.add(Artifact( + path: downloadedPath, + finalFileName: artifact, + )); + } else { + break; + } + } + + // Only provide complete set of artifacts. + if (artifactsForTarget.length == requiredArtifacts.length) { + _log.fine('Found precompiled artifacts for $target'); + res[target] = artifactsForTarget; + } + } + + return res; + } + + static Future _get(Uri url, {Map? headers}) async { + int attempt = 0; + const maxAttempts = 10; + while (true) { + try { + return await get(url, headers: headers); + } on SocketException catch (e) { + // Try to detect reset by peer error and retry. + if (attempt++ < maxAttempts && + (e.osError?.errorCode == 54 || e.osError?.errorCode == 10054)) { + _log.severe( + 'Failed to download $url: $e, attempt $attempt of $maxAttempts, will retry...'); + await Future.delayed(Duration(seconds: 1)); + continue; + } else { + rethrow; + } + } + } + } + + Future _tryDownloadArtifacts({ + required String crateHash, + required String fileName, + required String signatureFileName, + required String finalPath, + }) async { + final precompiledBinaries = environment.crateOptions.precompiledBinaries!; + final prefix = precompiledBinaries.uriPrefix; + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = Uri.parse('$prefix$crateHash/$signatureFileName'); + _log.fine('Downloading signature from $signatureUrl'); + final signature = await _get(signatureUrl); + if (signature.statusCode == 404) { + _log.warning( + 'Precompiled binaries not available for crate hash $crateHash ($fileName)'); + return; + } + if (signature.statusCode != 200) { + _log.severe( + 'Failed to download signature $signatureUrl: status ${signature.statusCode}'); + return; + } + _log.fine('Downloading binary from $url'); + final res = await _get(url); + if (res.statusCode != 200) { + _log.severe('Failed to download binary $url: status ${res.statusCode}'); + return; + } + if (verify( + precompiledBinaries.publicKey, res.bodyBytes, signature.bodyBytes)) { + File(finalPath).writeAsBytesSync(res.bodyBytes); + } else { + _log.shout('Signature verification failed! Ignoring binary.'); + } + } +} + +enum AritifactType { + staticlib, + dylib, +} + +AritifactType artifactTypeForTarget(Target target) { + if (target.darwinPlatform != null) { + return AritifactType.staticlib; + } else { + return AritifactType.dylib; + } +} + +List getArtifactNames({ + required Target target, + required String libraryName, + required bool remote, + AritifactType? aritifactType, +}) { + aritifactType ??= artifactTypeForTarget(target); + if (target.darwinArch != null) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.dylib']; + } + } else if (target.rust.contains('-windows-')) { + if (aritifactType == AritifactType.staticlib) { + return ['$libraryName.lib']; + } else { + return [ + '$libraryName.dll', + '$libraryName.dll.lib', + if (!remote) '$libraryName.pdb' + ]; + } + } else if (target.rust.contains('-linux-')) { + if (aritifactType == AritifactType.staticlib) { + return ['lib$libraryName.a']; + } else { + return ['lib$libraryName.so']; + } + } else { + throw Exception("Unsupported target: ${target.rust}"); + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart new file mode 100644 index 0000000000..9154371e00 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_cmake.dart @@ -0,0 +1,37 @@ +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +class BuildCMake { + final CargokitUserOptions userOptions; + + BuildCMake({required this.userOptions}); + + Future build() async { + final targetPlatform = Environment.targetPlatform; + final target = Target.forFlutterName(Environment.targetPlatform); + if (target == null) { + throw Exception("Unknown target platform: $targetPlatform"); + } + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts([target]); + + final libs = artifacts[target]!; + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path) + .copySync(path.join(Environment.outputDir, lib.finalFileName)); + } + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart new file mode 100644 index 0000000000..469c8b2d58 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_gradle.dart @@ -0,0 +1,46 @@ +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; + +final log = Logger('build_gradle'); + +class BuildGradle { + BuildGradle({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.targetPlatforms.map((arch) { + final target = Target.forFlutterName(arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}"); + } + return target; + }).toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: true); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts(targets); + + for (final target in targets) { + final libs = artifacts[target]!; + final outputDir = path.join(Environment.outputDir, target.android!); + Directory(outputDir).createSync(recursive: true); + + for (final lib in libs) { + if (lib.type == AritifactType.dylib) { + File(lib.path).copySync(path.join(outputDir, lib.finalFileName)); + } + } + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/build_pod.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_pod.dart new file mode 100644 index 0000000000..f01401e1cb --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_pod.dart @@ -0,0 +1,86 @@ +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'target.dart'; +import 'util.dart'; + +class BuildPod { + BuildPod({required this.userOptions}); + + final CargokitUserOptions userOptions; + + Future build() async { + final targets = Environment.darwinArchs.map((arch) { + final target = Target.forDarwin( + platformName: Environment.darwinPlatformName, darwinAarch: arch); + if (target == null) { + throw Exception( + "Unknown darwin target or platform: $arch, ${Environment.darwinPlatformName}"); + } + return target; + }).toList(); + + final environment = BuildEnvironment.fromEnvironment(isAndroid: false); + final provider = + ArtifactProvider(environment: environment, userOptions: userOptions); + final artifacts = await provider.getArtifacts(targets); + + void performLipo(String targetFile, Iterable sourceFiles) { + runCommand("lipo", [ + '-create', + ...sourceFiles, + '-output', + targetFile, + ]); + } + + final outputDir = Environment.outputDir; + + Directory(outputDir).createSync(recursive: true); + + final staticLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.staticlib) + .toList(); + final dynamicLibs = artifacts.values + .expand((element) => element) + .where((element) => element.type == AritifactType.dylib) + .toList(); + + final libName = environment.crateInfo.packageName; + + // If there is static lib, use it and link it with pod + if (staticLibs.isNotEmpty) { + final finalTargetFile = path.join(outputDir, "lib$libName.a"); + performLipo(finalTargetFile, staticLibs.map((e) => e.path)); + } else { + // Otherwise try to replace bundle dylib with our dylib + final bundlePaths = [ + '$libName.framework/Versions/A/$libName', + '$libName.framework/$libName', + ]; + + for (final bundlePath in bundlePaths) { + final targetFile = path.join(outputDir, bundlePath); + if (File(targetFile).existsSync()) { + performLipo(targetFile, dynamicLibs.map((e) => e.path)); + + // Replace absolute id with @rpath one so that it works properly + // when moved to Frameworks. + runCommand("install_name_tool", [ + '-id', + '@rpath/$bundlePath', + targetFile, + ]); + return; + } + } + throw Exception('Unable to find bundle for dynamic library'); + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/build_tool.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_tool.dart new file mode 100644 index 0000000000..1d9462af71 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/build_tool.dart @@ -0,0 +1,268 @@ +import 'dart:io'; + +import 'package:args/command_runner.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; + +import 'android_environment.dart'; +import 'build_cmake.dart'; +import 'build_gradle.dart'; +import 'build_pod.dart'; +import 'logging.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; +import 'util.dart'; +import 'verify_binaries.dart'; + +final log = Logger('build_tool'); + +abstract class BuildCommand extends Command { + Future runBuildCommand(CargokitUserOptions options); + + @override + Future run() async { + final options = CargokitUserOptions.load(); + + if (options.verboseLogging || + Platform.environment['CARGOKIT_VERBOSE'] == '1') { + enableVerboseLogging(); + } + + await runBuildCommand(options); + } +} + +class BuildPodCommand extends BuildCommand { + @override + final name = 'build-pod'; + + @override + final description = 'Build cocoa pod library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildPod(userOptions: options); + await build.build(); + } +} + +class BuildGradleCommand extends BuildCommand { + @override + final name = 'build-gradle'; + + @override + final description = 'Build android library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildGradle(userOptions: options); + await build.build(); + } +} + +class BuildCMakeCommand extends BuildCommand { + @override + final name = 'build-cmake'; + + @override + final description = 'Build CMake library'; + + @override + Future runBuildCommand(CargokitUserOptions options) async { + final build = BuildCMake(userOptions: options); + await build.build(); + } +} + +class GenKeyCommand extends Command { + @override + final name = 'gen-key'; + + @override + final description = 'Generate key pair for signing precompiled binaries'; + + @override + void run() { + final kp = generateKey(); + final private = HEX.encode(kp.privateKey.bytes); + final public = HEX.encode(kp.publicKey.bytes); + print("Private Key: $private"); + print("Public Key: $public"); + } +} + +class PrecompileBinariesCommand extends Command { + PrecompileBinariesCommand() { + argParser + ..addOption( + 'repository', + mandatory: true, + help: 'Github repository slug in format owner/name', + ) + ..addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ) + ..addMultiOption('target', + help: 'Rust target triple of artifact to build.\n' + 'Can be specified multiple times or omitted in which case\n' + 'all targets for current platform will be built.') + ..addOption( + 'android-sdk-location', + help: 'Location of Android SDK (if available)', + ) + ..addOption( + 'android-ndk-version', + help: 'Android NDK version (if available)', + ) + ..addOption( + 'android-min-sdk-version', + help: 'Android minimum rquired version (if available)', + ) + ..addOption( + 'temp-dir', + help: 'Directory to store temporary build artifacts', + ) + ..addFlag( + "verbose", + abbr: "v", + defaultsTo: false, + help: "Enable verbose logging", + ); + } + + @override + final name = 'precompile-binaries'; + + @override + final description = 'Prebuild and upload binaries\n' + 'Private key must be passed through PRIVATE_KEY environment variable. ' + 'Use gen_key through generate priave key.\n' + 'Github token must be passed as GITHUB_TOKEN environment variable.\n'; + + @override + Future run() async { + final verbose = argResults!['verbose'] as bool; + if (verbose) { + enableVerboseLogging(); + } + + final privateKeyString = Platform.environment['PRIVATE_KEY']; + if (privateKeyString == null) { + throw ArgumentError('Missing PRIVATE_KEY environment variable'); + } + final githubToken = Platform.environment['GITHUB_TOKEN']; + if (githubToken == null) { + throw ArgumentError('Missing GITHUB_TOKEN environment variable'); + } + final privateKey = HEX.decode(privateKeyString); + if (privateKey.length != 64) { + throw ArgumentError('Private key must be 64 bytes long'); + } + final manifestDir = argResults!['manifest-dir'] as String; + if (!Directory(manifestDir).existsSync()) { + throw ArgumentError('Manifest directory does not exist: $manifestDir'); + } + String? androidMinSdkVersionString = + argResults!['android-min-sdk-version'] as String?; + int? androidMinSdkVersion; + if (androidMinSdkVersionString != null) { + androidMinSdkVersion = int.tryParse(androidMinSdkVersionString); + if (androidMinSdkVersion == null) { + throw ArgumentError( + 'Invalid android-min-sdk-version: $androidMinSdkVersionString'); + } + } + final targetStrigns = argResults!['target'] as List; + final targets = targetStrigns.map((target) { + final res = Target.forRustTriple(target); + if (res == null) { + throw ArgumentError('Invalid target: $target'); + } + return res; + }).toList(growable: false); + final precompileBinaries = PrecompileBinaries( + privateKey: PrivateKey(privateKey), + githubToken: githubToken, + manifestDir: manifestDir, + repositorySlug: RepositorySlug.full(argResults!['repository'] as String), + targets: targets, + androidSdkLocation: argResults!['android-sdk-location'] as String?, + androidNdkVersion: argResults!['android-ndk-version'] as String?, + androidMinSdkVersion: androidMinSdkVersion, + tempDir: argResults!['temp-dir'] as String?, + ); + + await precompileBinaries.run(); + } +} + +class VerifyBinariesCommand extends Command { + VerifyBinariesCommand() { + argParser.addOption( + 'manifest-dir', + mandatory: true, + help: 'Directory containing Cargo.toml', + ); + } + + @override + final name = "verify-binaries"; + + @override + final description = 'Verifies published binaries\n' + 'Checks whether there is a binary published for each targets\n' + 'and checks the signature.'; + + @override + Future run() async { + final manifestDir = argResults!['manifest-dir'] as String; + final verifyBinaries = VerifyBinaries( + manifestDir: manifestDir, + ); + await verifyBinaries.run(); + } +} + +Future runMain(List args) async { + try { + // Init logging before options are loaded + initLogging(); + + if (Platform.environment['_CARGOKIT_NDK_LINK_TARGET'] != null) { + return AndroidEnvironment.clangLinkerWrapper(args); + } + + final runner = CommandRunner('build_tool', 'Cargokit built_tool') + ..addCommand(BuildPodCommand()) + ..addCommand(BuildGradleCommand()) + ..addCommand(BuildCMakeCommand()) + ..addCommand(GenKeyCommand()) + ..addCommand(PrecompileBinariesCommand()) + ..addCommand(VerifyBinariesCommand()); + + await runner.run(args); + } on ArgumentError catch (e) { + stderr.writeln(e.toString()); + exit(1); + } catch (e, s) { + log.severe(kDoubleSeparator); + log.severe('Cargokit BuildTool failed with error:'); + log.severe(kSeparator); + log.severe(e); + // This tells user to install Rust, there's no need to pollute the log with + // stack trace. + if (e is! RustupNotFoundException) { + log.severe(kSeparator); + log.severe(s); + log.severe(kSeparator); + log.severe('BuildTool arguments: $args'); + } + log.severe(kDoubleSeparator); + exit(1); + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/builder.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/builder.dart new file mode 100644 index 0000000000..570a5375e4 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/builder.dart @@ -0,0 +1,195 @@ +import 'package:collection/collection.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'android_environment.dart'; +import 'cargo.dart'; +import 'environment.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; +import 'util.dart'; + +final _log = Logger('builder'); + +enum BuildConfiguration { + debug, + release, + profile, +} + +extension on BuildConfiguration { + bool get isDebug => this == BuildConfiguration.debug; + String get rustName => switch (this) { + BuildConfiguration.debug => 'debug', + BuildConfiguration.release => 'release', + BuildConfiguration.profile => 'release', + }; +} + +class BuildException implements Exception { + final String message; + + BuildException(this.message); + + @override + String toString() { + return 'BuildException: $message'; + } +} + +class BuildEnvironment { + final BuildConfiguration configuration; + final CargokitCrateOptions crateOptions; + final String targetTempDir; + final String manifestDir; + final CrateInfo crateInfo; + + final bool isAndroid; + final String? androidSdkPath; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? javaHome; + + BuildEnvironment({ + required this.configuration, + required this.crateOptions, + required this.targetTempDir, + required this.manifestDir, + required this.crateInfo, + required this.isAndroid, + this.androidSdkPath, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.javaHome, + }); + + static BuildConfiguration parseBuildConfiguration(String value) { + // XCode configuration adds the flavor to configuration name. + final firstSegment = value.split('-').first; + final buildConfiguration = BuildConfiguration.values.firstWhereOrNull( + (e) => e.name == firstSegment, + ); + if (buildConfiguration == null) { + _log.warning('Unknown build configuraiton $value, will assume release'); + return BuildConfiguration.release; + } + return buildConfiguration; + } + + static BuildEnvironment fromEnvironment({ + required bool isAndroid, + }) { + final buildConfiguration = + parseBuildConfiguration(Environment.configuration); + final manifestDir = Environment.manifestDir; + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + final crateInfo = CrateInfo.load(manifestDir); + return BuildEnvironment( + configuration: buildConfiguration, + crateOptions: crateOptions, + targetTempDir: Environment.targetTempDir, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: isAndroid, + androidSdkPath: isAndroid ? Environment.sdkPath : null, + androidNdkVersion: isAndroid ? Environment.ndkVersion : null, + androidMinSdkVersion: + isAndroid ? int.parse(Environment.minSdkVersion) : null, + javaHome: isAndroid ? Environment.javaHome : null, + ); + } +} + +class RustBuilder { + final Target target; + final BuildEnvironment environment; + + RustBuilder({ + required this.target, + required this.environment, + }); + + void prepare( + Rustup rustup, + ) { + final toolchain = _toolchain; + if (rustup.installedTargets(toolchain) == null) { + rustup.installToolchain(toolchain); + } + if (toolchain == 'nightly') { + rustup.installRustSrcForNightly(); + } + if (!rustup.installedTargets(toolchain)!.contains(target.rust)) { + rustup.installTarget(target.rust, toolchain: toolchain); + } + } + + CargoBuildOptions? get _buildOptions => + environment.crateOptions.cargo[environment.configuration]; + + String get _toolchain => _buildOptions?.toolchain.name ?? 'stable'; + + /// Returns the path of directory containing build artifacts. + Future build() async { + final extraArgs = _buildOptions?.flags ?? []; + final manifestPath = path.join(environment.manifestDir, 'Cargo.toml'); + runCommand( + 'rustup', + [ + 'run', + _toolchain, + 'cargo', + 'build', + ...extraArgs, + '--manifest-path', + manifestPath, + '-p', + environment.crateInfo.packageName, + if (!environment.configuration.isDebug) '--release', + '--target', + target.rust, + '--target-dir', + environment.targetTempDir, + ], + environment: await _buildEnvironment(), + ); + return path.join( + environment.targetTempDir, + target.rust, + environment.configuration.rustName, + ); + } + + Future> _buildEnvironment() async { + if (target.android == null) { + return {}; + } else { + final sdkPath = environment.androidSdkPath; + final ndkVersion = environment.androidNdkVersion; + final minSdkVersion = environment.androidMinSdkVersion; + if (sdkPath == null) { + throw BuildException('androidSdkPath is not set'); + } + if (ndkVersion == null) { + throw BuildException('androidNdkVersion is not set'); + } + if (minSdkVersion == null) { + throw BuildException('androidMinSdkVersion is not set'); + } + final env = AndroidEnvironment( + sdkPath: sdkPath, + ndkVersion: ndkVersion, + minSdkVersion: minSdkVersion, + targetTempDir: environment.targetTempDir, + target: target, + ); + if (!env.ndkIsInstalled() && environment.javaHome != null) { + env.installNdk(javaHome: environment.javaHome!); + } + return env.buildEnvironment(); + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/cargo.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/cargo.dart new file mode 100644 index 0000000000..0d4483ff58 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/cargo.dart @@ -0,0 +1,45 @@ +import 'dart:io'; + +import 'package:path/path.dart' as path; +import 'package:toml/toml.dart'; + +class ManifestException { + ManifestException(this.message, {required this.fileName}); + + final String? fileName; + final String message; + + @override + String toString() { + if (fileName != null) { + return 'Failed to parse package manifest at $fileName: $message'; + } else { + return 'Failed to parse package manifest: $message'; + } + } +} + +class CrateInfo { + CrateInfo({required this.packageName}); + + final String packageName; + + static CrateInfo parseManifest(String manifest, {final String? fileName}) { + final toml = TomlDocument.parse(manifest); + final package = toml.toMap()['package']; + if (package == null) { + throw ManifestException('Missing package section', fileName: fileName); + } + final name = package['name']; + if (name == null) { + throw ManifestException('Missing package name', fileName: fileName); + } + return CrateInfo(packageName: name); + } + + static CrateInfo load(String manifestDir) { + final manifestFile = File(path.join(manifestDir, 'Cargo.toml')); + final manifest = manifestFile.readAsStringSync(); + return parseManifest(manifest, fileName: manifestFile.path); + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart new file mode 100644 index 0000000000..e58c37ff90 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/crate_hash.dart @@ -0,0 +1,121 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:collection/collection.dart'; +import 'package:convert/convert.dart'; +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as path; + +class CrateHash { + /// Computes a hash uniquely identifying crate content. This takes into account + /// content all all .rs files inside the src directory, as well as Cargo.toml, + /// Cargo.lock, build.rs and cargokit.yaml. + /// + /// If [tempStorage] is provided, computed hash is stored in a file in that directory + /// and reused on subsequent calls if the crate content hasn't changed. + static String compute(String manifestDir, {String? tempStorage}) { + return CrateHash._( + manifestDir: manifestDir, + tempStorage: tempStorage, + )._compute(); + } + + CrateHash._({ + required this.manifestDir, + required this.tempStorage, + }); + + String _compute() { + final files = getFiles(); + final tempStorage = this.tempStorage; + if (tempStorage != null) { + final quickHash = _computeQuickHash(files); + final quickHashFolder = Directory(path.join(tempStorage, 'crate_hash')); + quickHashFolder.createSync(recursive: true); + final quickHashFile = File(path.join(quickHashFolder.path, quickHash)); + if (quickHashFile.existsSync()) { + return quickHashFile.readAsStringSync(); + } + final hash = _computeHash(files); + quickHashFile.writeAsStringSync(hash); + return hash; + } else { + return _computeHash(files); + } + } + + /// Computes a quick hash based on files stat (without reading contents). This + /// is used to cache the real hash, which is slower to compute since it involves + /// reading every single file. + String _computeQuickHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + final data = ByteData(8); + for (final file in files) { + input.add(utf8.encode(file.path)); + final stat = file.statSync(); + data.setUint64(0, stat.size); + input.add(data.buffer.asUint8List()); + data.setUint64(0, stat.modified.millisecondsSinceEpoch); + input.add(data.buffer.asUint8List()); + } + + input.close(); + return base64Url.encode(output.events.single.bytes); + } + + String _computeHash(List files) { + final output = AccumulatorSink(); + final input = sha256.startChunkedConversion(output); + + void addTextFile(File file) { + // text Files are hashed by lines in case we're dealing with github checkout + // that auto-converts line endings. + final splitter = LineSplitter(); + if (file.existsSync()) { + final data = file.readAsStringSync(); + final lines = splitter.convert(data); + for (final line in lines) { + input.add(utf8.encode(line)); + } + } + } + + for (final file in files) { + addTextFile(file); + } + + input.close(); + final res = output.events.single; + + // Truncate to 128bits. + final hash = res.bytes.sublist(0, 16); + return hex.encode(hash); + } + + List getFiles() { + final src = Directory(path.join(manifestDir, 'src')); + final files = src + .listSync(recursive: true, followLinks: false) + .whereType() + .toList(); + files.sortBy((element) => element.path); + void addFile(String relative) { + final file = File(path.join(manifestDir, relative)); + if (file.existsSync()) { + files.add(file); + } + } + + addFile('Cargo.toml'); + addFile('Cargo.lock'); + addFile('build.rs'); + addFile('cargokit.yaml'); + return files; + } + + final String manifestDir; + final String? tempStorage; +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/environment.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/environment.dart new file mode 100644 index 0000000000..1d267edb10 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/environment.dart @@ -0,0 +1,65 @@ +import 'dart:io'; + +extension on String { + String resolveSymlink() => File(this).resolveSymbolicLinksSync(); +} + +class Environment { + /// Current build configuration (debug or release). + static String get configuration => + _getEnv("CARGOKIT_CONFIGURATION").toLowerCase(); + + static bool get isDebug => configuration == 'debug'; + static bool get isRelease => configuration == 'release'; + + /// Temporary directory where Rust build artifacts are placed. + static String get targetTempDir => _getEnv("CARGOKIT_TARGET_TEMP_DIR"); + + /// Final output directory where the build artifacts are placed. + static String get outputDir => _getEnvPath('CARGOKIT_OUTPUT_DIR'); + + /// Path to the crate manifest (containing Cargo.toml). + static String get manifestDir => _getEnvPath('CARGOKIT_MANIFEST_DIR'); + + /// Directory inside root project. Not necessarily root folder. Symlinks are + /// not resolved on purpose. + static String get rootProjectDir => _getEnv('CARGOKIT_ROOT_PROJECT_DIR'); + + // Pod + + /// Platform name (macosx, iphoneos, iphonesimulator). + static String get darwinPlatformName => + _getEnv("CARGOKIT_DARWIN_PLATFORM_NAME"); + + /// List of architectures to build for (arm64, armv7, x86_64). + static List get darwinArchs => + _getEnv("CARGOKIT_DARWIN_ARCHS").split(' '); + + // Gradle + static String get minSdkVersion => _getEnv("CARGOKIT_MIN_SDK_VERSION"); + static String get ndkVersion => _getEnv("CARGOKIT_NDK_VERSION"); + static String get sdkPath => _getEnvPath("CARGOKIT_SDK_DIR"); + static String get javaHome => _getEnvPath("CARGOKIT_JAVA_HOME"); + static List get targetPlatforms => + _getEnv("CARGOKIT_TARGET_PLATFORMS").split(','); + + // CMAKE + static String get targetPlatform => _getEnv("CARGOKIT_TARGET_PLATFORM"); + + static String _getEnv(String key) { + final res = Platform.environment[key]; + if (res == null) { + throw Exception("Missing environment variable $key"); + } + return res; + } + + static String _getEnvPath(String key) { + final res = _getEnv(key); + if (Directory(res).existsSync()) { + return res.resolveSymlink(); + } else { + return res; + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/logging.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/logging.dart new file mode 100644 index 0000000000..06392b9931 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/logging.dart @@ -0,0 +1,49 @@ +import 'dart:io'; + +import 'package:logging/logging.dart'; + +const String kSeparator = "--"; +const String kDoubleSeparator = "=="; + +bool _lastMessageWasSeparator = false; + +void _log(LogRecord rec) { + final prefix = '${rec.level.name}: '; + final out = rec.level == Level.SEVERE ? stderr : stdout; + if (rec.message == kSeparator) { + if (!_lastMessageWasSeparator) { + out.write(prefix); + out.writeln('-' * 80); + _lastMessageWasSeparator = true; + } + return; + } else if (rec.message == kDoubleSeparator) { + out.write(prefix); + out.writeln('=' * 80); + _lastMessageWasSeparator = true; + return; + } + out.write(prefix); + out.writeln(rec.message); + _lastMessageWasSeparator = false; +} + +void initLogging() { + Logger.root.level = Level.INFO; + Logger.root.onRecord.listen((LogRecord rec) { + final lines = rec.message.split('\n'); + for (final line in lines) { + if (line.isNotEmpty || lines.length == 1 || line != lines.last) { + _log(LogRecord( + rec.level, + line, + rec.loggerName, + )); + } + } + }); +} + +void enableVerboseLogging() { + Logger.root.level = Level.ALL; +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/options.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/options.dart new file mode 100644 index 0000000000..7937dcacdb --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/options.dart @@ -0,0 +1,306 @@ +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:hex/hex.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; +import 'package:source_span/source_span.dart'; +import 'package:yaml/yaml.dart'; + +import 'builder.dart'; +import 'environment.dart'; +import 'rustup.dart'; + +final _log = Logger('options'); + +/// A class for exceptions that have source span information attached. +class SourceSpanException implements Exception { + // This is a getter so that subclasses can override it. + /// A message describing the exception. + String get message => _message; + final String _message; + + // This is a getter so that subclasses can override it. + /// The span associated with this exception. + /// + /// This may be `null` if the source location can't be determined. + SourceSpan? get span => _span; + final SourceSpan? _span; + + SourceSpanException(this._message, this._span); + + /// Returns a string representation of `this`. + /// + /// [color] may either be a [String], a [bool], or `null`. If it's a string, + /// it indicates an ANSI terminal color escape that should be used to + /// highlight the span's text. If it's `true`, it indicates that the text + /// should be highlighted using the default color. If it's `false` or `null`, + /// it indicates that the text shouldn't be highlighted. + @override + String toString({Object? color}) { + if (span == null) return message; + return 'Error on ${span!.message(message, color: color)}'; + } +} + +enum Toolchain { + stable, + beta, + nightly, +} + +class CargoBuildOptions { + final Toolchain toolchain; + final List flags; + + CargoBuildOptions({ + required this.toolchain, + required this.flags, + }); + + static Toolchain _toolchainFromNode(YamlNode node) { + if (node case YamlScalar(value: String name)) { + final toolchain = + Toolchain.values.firstWhereOrNull((element) => element.name == name); + if (toolchain != null) { + return toolchain; + } + } + throw SourceSpanException( + 'Unknown toolchain. Must be one of ${Toolchain.values.map((e) => e.name)}.', + node.span); + } + + static CargoBuildOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + Toolchain toolchain = Toolchain.stable; + List flags = []; + for (final MapEntry(:key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: 'toolchain')) { + toolchain = _toolchainFromNode(value); + } else if (key case YamlScalar(value: 'extra_flags')) { + if (value case YamlList(nodes: List list)) { + if (list.every((element) { + if (element case YamlScalar(value: String _)) { + return true; + } + return false; + })) { + flags = list.map((e) => e.value as String).toList(); + continue; + } + } + throw SourceSpanException( + 'Extra flags must be a list of strings', value.span); + } else { + throw SourceSpanException( + 'Unknown cargo option type. Must be "toolchain" or "extra_flags".', + key.span); + } + } + return CargoBuildOptions(toolchain: toolchain, flags: flags); + } +} + +extension on YamlMap { + /// Map that extracts keys so that we can do map case check on them. + Map get valueMap => + nodes.map((key, value) => MapEntry(key.value, value)); +} + +class PrecompiledBinaries { + final String uriPrefix; + final PublicKey publicKey; + + PrecompiledBinaries({ + required this.uriPrefix, + required this.publicKey, + }); + + static PublicKey _publicKeyFromHex(String key, SourceSpan? span) { + final bytes = HEX.decode(key); + if (bytes.length != 32) { + throw SourceSpanException( + 'Invalid public key. Must be 32 bytes long.', span); + } + return PublicKey(bytes); + } + + static PrecompiledBinaries parse(YamlNode node) { + if (node case YamlMap(valueMap: Map map)) { + if (map + case { + 'url_prefix': YamlNode urlPrefixNode, + 'public_key': YamlNode publicKeyNode, + }) { + final urlPrefix = switch (urlPrefixNode) { + YamlScalar(value: String urlPrefix) => urlPrefix, + _ => throw SourceSpanException( + 'Invalid URL prefix value.', urlPrefixNode.span), + }; + final publicKey = switch (publicKeyNode) { + YamlScalar(value: String publicKey) => + _publicKeyFromHex(publicKey, publicKeyNode.span), + _ => throw SourceSpanException( + 'Invalid public key value.', publicKeyNode.span), + }; + return PrecompiledBinaries( + uriPrefix: urlPrefix, + publicKey: publicKey, + ); + } + } + throw SourceSpanException( + 'Invalid precompiled binaries value. ' + 'Expected Map with "url_prefix" and "public_key".', + node.span); + } +} + +/// Cargokit options specified for Rust crate. +class CargokitCrateOptions { + CargokitCrateOptions({ + this.cargo = const {}, + this.precompiledBinaries, + }); + + final Map cargo; + final PrecompiledBinaries? precompiledBinaries; + + static CargokitCrateOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + final options = {}; + PrecompiledBinaries? precompiledBinaries; + + for (final entry in node.nodes.entries) { + if (entry + case MapEntry( + key: YamlScalar(value: 'cargo'), + value: YamlNode node, + )) { + if (node is! YamlMap) { + throw SourceSpanException('Cargo options must be a map', node.span); + } + for (final MapEntry(:YamlNode key, :value) in node.nodes.entries) { + if (key case YamlScalar(value: String name)) { + final configuration = BuildConfiguration.values + .firstWhereOrNull((element) => element.name == name); + if (configuration != null) { + options[configuration] = CargoBuildOptions.parse(value); + continue; + } + } + throw SourceSpanException( + 'Unknown build configuration. Must be one of ${BuildConfiguration.values.map((e) => e.name)}.', + key.span); + } + } else if (entry.key case YamlScalar(value: 'precompiled_binaries')) { + precompiledBinaries = PrecompiledBinaries.parse(entry.value); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "cargo" or "precompiled_binaries".', + entry.key.span); + } + } + return CargokitCrateOptions( + cargo: options, + precompiledBinaries: precompiledBinaries, + ); + } + + static CargokitCrateOptions load({ + required String manifestDir, + }) { + final uri = Uri.file(path.join(manifestDir, "cargokit.yaml")); + final file = File.fromUri(uri); + if (file.existsSync()) { + final contents = loadYamlNode(file.readAsStringSync(), sourceUrl: uri); + return parse(contents); + } else { + return CargokitCrateOptions(); + } + } +} + +class CargokitUserOptions { + // When Rustup is installed always build locally unless user opts into + // using precompiled binaries. + static bool defaultUsePrecompiledBinaries() { + return Rustup.executablePath() == null; + } + + CargokitUserOptions({ + required this.usePrecompiledBinaries, + required this.verboseLogging, + }); + + CargokitUserOptions._() + : usePrecompiledBinaries = defaultUsePrecompiledBinaries(), + verboseLogging = false; + + static CargokitUserOptions parse(YamlNode node) { + if (node is! YamlMap) { + throw SourceSpanException('Cargokit options must be a map', node.span); + } + bool usePrecompiledBinaries = defaultUsePrecompiledBinaries(); + bool verboseLogging = false; + + for (final entry in node.nodes.entries) { + if (entry.key case YamlScalar(value: 'use_precompiled_binaries')) { + if (entry.value case YamlScalar(value: bool value)) { + usePrecompiledBinaries = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "use_precompiled_binaries". Must be a boolean.', + entry.value.span); + } else if (entry.key case YamlScalar(value: 'verbose_logging')) { + if (entry.value case YamlScalar(value: bool value)) { + verboseLogging = value; + continue; + } + throw SourceSpanException( + 'Invalid value for "verbose_logging". Must be a boolean.', + entry.value.span); + } else { + throw SourceSpanException( + 'Unknown cargokit option type. Must be "use_precompiled_binaries" or "verbose_logging".', + entry.key.span); + } + } + return CargokitUserOptions( + usePrecompiledBinaries: usePrecompiledBinaries, + verboseLogging: verboseLogging, + ); + } + + static CargokitUserOptions load() { + String fileName = "cargokit_options.yaml"; + var userProjectDir = Directory(Environment.rootProjectDir); + + while (userProjectDir.parent.path != userProjectDir.path) { + final configFile = File(path.join(userProjectDir.path, fileName)); + if (configFile.existsSync()) { + final contents = loadYamlNode( + configFile.readAsStringSync(), + sourceUrl: configFile.uri, + ); + final res = parse(contents); + if (res.verboseLogging) { + _log.info('Found user options file at ${configFile.path}'); + } + return res; + } + userProjectDir = userProjectDir.parent; + } + return CargokitUserOptions._(); + } + + final bool usePrecompiledBinaries; + final bool verboseLogging; +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart new file mode 100644 index 0000000000..39ffafc451 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/precompile_binaries.dart @@ -0,0 +1,199 @@ +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:github/github.dart'; +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'artifacts_provider.dart'; +import 'builder.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'rustup.dart'; +import 'target.dart'; + +final _log = Logger('precompile_binaries'); + +class PrecompileBinaries { + PrecompileBinaries({ + required this.privateKey, + required this.githubToken, + required this.repositorySlug, + required this.manifestDir, + required this.targets, + this.androidSdkLocation, + this.androidNdkVersion, + this.androidMinSdkVersion, + this.tempDir, + }); + + final PrivateKey privateKey; + final String githubToken; + final RepositorySlug repositorySlug; + final String manifestDir; + final List targets; + final String? androidSdkLocation; + final String? androidNdkVersion; + final int? androidMinSdkVersion; + final String? tempDir; + + static String fileName(Target target, String name) { + return '${target.rust}_$name'; + } + + static String signatureFileName(Target target, String name) { + return '${target.rust}_$name.sig'; + } + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final targets = List.of(this.targets); + if (targets.isEmpty) { + targets.addAll([ + ...Target.buildableTargets(), + if (androidSdkLocation != null) ...Target.androidTargets(), + ]); + } + + _log.info('Precompiling binaries for $targets'); + + final hash = CrateHash.compute(manifestDir); + _log.info('Computed crate hash: $hash'); + + final String tagName = 'precompiled_$hash'; + + final github = GitHub(auth: Authentication.withToken(githubToken)); + final repo = github.repositories; + final release = await _getOrCreateRelease( + repo: repo, + tagName: tagName, + packageName: crateInfo.packageName, + hash: hash, + ); + + final tempDir = this.tempDir != null + ? Directory(this.tempDir!) + : Directory.systemTemp.createTempSync('precompiled_'); + + tempDir.createSync(recursive: true); + + final crateOptions = CargokitCrateOptions.load( + manifestDir: manifestDir, + ); + + final buildEnvironment = BuildEnvironment( + configuration: BuildConfiguration.release, + crateOptions: crateOptions, + targetTempDir: tempDir.path, + manifestDir: manifestDir, + crateInfo: crateInfo, + isAndroid: androidSdkLocation != null, + androidSdkPath: androidSdkLocation, + androidNdkVersion: androidNdkVersion, + androidMinSdkVersion: androidMinSdkVersion, + ); + + final rustup = Rustup(); + + for (final target in targets) { + final artifactNames = getArtifactNames( + target: target, + libraryName: crateInfo.packageName, + remote: true, + ); + + if (artifactNames.every((name) { + final fileName = PrecompileBinaries.fileName(target, name); + return (release.assets ?? []).any((e) => e.name == fileName); + })) { + _log.info("All artifacts for $target already exist - skipping"); + continue; + } + + _log.info('Building for $target'); + + final builder = + RustBuilder(target: target, environment: buildEnvironment); + builder.prepare(rustup); + final res = await builder.build(); + + final assets = []; + for (final name in artifactNames) { + final file = File(path.join(res, name)); + if (!file.existsSync()) { + throw Exception('Missing artifact: ${file.path}'); + } + + final data = file.readAsBytesSync(); + final create = CreateReleaseAsset( + name: PrecompileBinaries.fileName(target, name), + contentType: "application/octet-stream", + assetData: data, + ); + final signature = sign(privateKey, data); + final signatureCreate = CreateReleaseAsset( + name: signatureFileName(target, name), + contentType: "application/octet-stream", + assetData: signature, + ); + bool verified = verify(public(privateKey), data, signature); + if (!verified) { + throw Exception('Signature verification failed'); + } + assets.add(create); + assets.add(signatureCreate); + } + _log.info('Uploading assets: ${assets.map((e) => e.name)}'); + for (final asset in assets) { + // This seems to be failing on CI so do it one by one + int retryCount = 0; + while (true) { + try { + await repo.uploadReleaseAssets(release, [asset]); + break; + } on Exception catch (e) { + if (retryCount == 10) { + rethrow; + } + ++retryCount; + _log.shout( + 'Upload failed (attempt $retryCount, will retry): ${e.toString()}'); + await Future.delayed(Duration(seconds: 2)); + } + } + } + } + + _log.info('Cleaning up'); + tempDir.deleteSync(recursive: true); + } + + Future _getOrCreateRelease({ + required RepositoriesService repo, + required String tagName, + required String packageName, + required String hash, + }) async { + Release release; + try { + _log.info('Fetching release $tagName'); + release = await repo.getReleaseByTagName(repositorySlug, tagName); + } on ReleaseNotFound { + _log.info('Release not found - creating release $tagName'); + release = await repo.createRelease( + repositorySlug, + CreateRelease.from( + tagName: tagName, + name: 'Precompiled binaries ${hash.substring(0, 8)}', + targetCommitish: null, + isDraft: false, + isPrerelease: false, + body: 'Precompiled binaries for crate $packageName, ' + 'crate hash $hash.', + )); + } + return release; + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/rustup.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/rustup.dart new file mode 100644 index 0000000000..f284179a4a --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/rustup.dart @@ -0,0 +1,133 @@ +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:path/path.dart' as path; + +import 'util.dart'; + +class _Toolchain { + _Toolchain( + this.name, + this.targets, + ); + + final String name; + final List targets; +} + +class Rustup { + List? installedTargets(String toolchain) { + final targets = _installedTargets(toolchain); + return targets != null ? List.unmodifiable(targets) : null; + } + + void installToolchain(String toolchain) { + log.info("Installing Rust toolchain: $toolchain"); + runCommand("rustup", ['toolchain', 'install', toolchain]); + _installedToolchains + .add(_Toolchain(toolchain, _getInstalledTargets(toolchain))); + } + + void installTarget( + String target, { + required String toolchain, + }) { + log.info("Installing Rust target: $target"); + runCommand("rustup", [ + 'target', + 'add', + '--toolchain', + toolchain, + target, + ]); + _installedTargets(toolchain)?.add(target); + } + + final List<_Toolchain> _installedToolchains; + + Rustup() : _installedToolchains = _getInstalledToolchains(); + + List? _installedTargets(String toolchain) => _installedToolchains + .firstWhereOrNull( + (e) => e.name == toolchain || e.name.startsWith('$toolchain-')) + ?.targets; + + static List<_Toolchain> _getInstalledToolchains() { + String extractToolchainName(String line) { + // ignore (default) after toolchain name + final parts = line.split(' '); + return parts[0]; + } + + final res = runCommand("rustup", ['toolchain', 'list']); + + // To list all non-custom toolchains, we need to filter out lines that + // don't start with "stable", "beta", or "nightly". + Pattern nonCustom = RegExp(r"^(stable|beta|nightly)"); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty && e.startsWith(nonCustom)) + .map(extractToolchainName) + .toList(growable: true); + + return lines + .map( + (name) => _Toolchain( + name, + _getInstalledTargets(name), + ), + ) + .toList(growable: true); + } + + static List _getInstalledTargets(String toolchain) { + final res = runCommand("rustup", [ + 'target', + 'list', + '--toolchain', + toolchain, + '--installed', + ]); + final lines = res.stdout + .toString() + .split('\n') + .where((e) => e.isNotEmpty) + .toList(growable: true); + return lines; + } + + bool _didInstallRustSrcForNightly = false; + + void installRustSrcForNightly() { + if (_didInstallRustSrcForNightly) { + return; + } + // Useful for -Z build-std + runCommand( + "rustup", + ['component', 'add', 'rust-src', '--toolchain', 'nightly'], + ); + _didInstallRustSrcForNightly = true; + } + + static String? executablePath() { + final envPath = Platform.environment['PATH']; + final envPathSeparator = Platform.isWindows ? ';' : ':'; + final home = Platform.isWindows + ? Platform.environment['USERPROFILE'] + : Platform.environment['HOME']; + final paths = [ + if (home != null) path.join(home, '.cargo', 'bin'), + if (envPath != null) ...envPath.split(envPathSeparator), + ]; + for (final p in paths) { + final rustup = Platform.isWindows ? 'rustup.exe' : 'rustup'; + final rustupPath = path.join(p, rustup); + if (File(rustupPath).existsSync()) { + return rustupPath; + } + } + return null; + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/target.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/target.dart new file mode 100644 index 0000000000..9287b23c7d --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/target.dart @@ -0,0 +1,137 @@ +import 'dart:io'; + +import 'package:collection/collection.dart'; + +import 'util.dart'; + +class Target { + Target({ + required this.rust, + this.flutter, + this.android, + this.androidMinSdkVersion, + this.darwinPlatform, + this.darwinArch, + }); + + static final all = [ + Target( + rust: 'armv7-linux-androideabi', + flutter: 'android-arm', + android: 'armeabi-v7a', + androidMinSdkVersion: 16, + ), + Target( + rust: 'aarch64-linux-android', + flutter: 'android-arm64', + android: 'arm64-v8a', + androidMinSdkVersion: 21, + ), + Target( + rust: 'i686-linux-android', + flutter: 'android-x86', + android: 'x86', + androidMinSdkVersion: 16, + ), + Target( + rust: 'x86_64-linux-android', + flutter: 'android-x64', + android: 'x86_64', + androidMinSdkVersion: 21, + ), + Target( + rust: 'x86_64-pc-windows-msvc', + flutter: 'windows-x64', + ), + Target( + rust: 'x86_64-unknown-linux-gnu', + flutter: 'linux-x64', + ), + Target( + rust: 'aarch64-unknown-linux-gnu', + flutter: 'linux-arm64', + ), + Target( + rust: 'x86_64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'x86_64', + ), + Target( + rust: 'aarch64-apple-darwin', + darwinPlatform: 'macosx', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios', + darwinPlatform: 'iphoneos', + darwinArch: 'arm64', + ), + Target( + rust: 'aarch64-apple-ios-sim', + darwinPlatform: 'iphonesimulator', + darwinArch: 'arm64', + ), + Target( + rust: 'x86_64-apple-ios', + darwinPlatform: 'iphonesimulator', + darwinArch: 'x86_64', + ), + ]; + + static Target? forFlutterName(String flutterName) { + return all.firstWhereOrNull((element) => element.flutter == flutterName); + } + + static Target? forDarwin({ + required String platformName, + required String darwinAarch, + }) { + return all.firstWhereOrNull((element) => // + element.darwinPlatform == platformName && + element.darwinArch == darwinAarch); + } + + static Target? forRustTriple(String triple) { + return all.firstWhereOrNull((element) => element.rust == triple); + } + + static List androidTargets() { + return all + .where((element) => element.android != null) + .toList(growable: false); + } + + /// Returns buildable targets on current host platform ignoring Android targets. + static List buildableTargets() { + if (Platform.isLinux) { + // Right now we don't support cross-compiling on Linux. So we just return + // the host target. + final arch = runCommand('arch', []).stdout as String; + if (arch.trim() == 'aarch64') { + return [Target.forRustTriple('aarch64-unknown-linux-gnu')!]; + } else { + return [Target.forRustTriple('x86_64-unknown-linux-gnu')!]; + } + } + return all.where((target) { + if (Platform.isWindows) { + return target.rust.contains('-windows-'); + } else if (Platform.isMacOS) { + return target.darwinPlatform != null; + } + return false; + }).toList(growable: false); + } + + @override + String toString() { + return rust; + } + + final String? flutter; + final String rust; + final String? android; + final int? androidMinSdkVersion; + final String? darwinPlatform; + final String? darwinArch; +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/util.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/util.dart new file mode 100644 index 0000000000..d8e30196da --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/util.dart @@ -0,0 +1,169 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:logging/logging.dart'; +import 'package:path/path.dart' as path; + +import 'logging.dart'; +import 'rustup.dart'; + +final log = Logger("process"); + +class CommandFailedException implements Exception { + final String executable; + final List arguments; + final ProcessResult result; + + CommandFailedException({ + required this.executable, + required this.arguments, + required this.result, + }); + + @override + String toString() { + final stdout = result.stdout.toString().trim(); + final stderr = result.stderr.toString().trim(); + return [ + "External Command: $executable ${arguments.map((e) => '"$e"').join(' ')}", + "Returned Exit Code: ${result.exitCode}", + kSeparator, + "STDOUT:", + if (stdout.isNotEmpty) stdout, + kSeparator, + "STDERR:", + if (stderr.isNotEmpty) stderr, + ].join('\n'); + } +} + +class TestRunCommandArgs { + final String executable; + final List arguments; + final String? workingDirectory; + final Map? environment; + final bool includeParentEnvironment; + final bool runInShell; + final Encoding? stdoutEncoding; + final Encoding? stderrEncoding; + + TestRunCommandArgs({ + required this.executable, + required this.arguments, + this.workingDirectory, + this.environment, + this.includeParentEnvironment = true, + this.runInShell = false, + this.stdoutEncoding, + this.stderrEncoding, + }); +} + +class TestRunCommandResult { + TestRunCommandResult({ + this.pid = 1, + this.exitCode = 0, + this.stdout = '', + this.stderr = '', + }); + + final int pid; + final int exitCode; + final String stdout; + final String stderr; +} + +TestRunCommandResult Function(TestRunCommandArgs args)? testRunCommandOverride; + +ProcessResult runCommand( + String executable, + List arguments, { + String? workingDirectory, + Map? environment, + bool includeParentEnvironment = true, + bool runInShell = false, + Encoding? stdoutEncoding = systemEncoding, + Encoding? stderrEncoding = systemEncoding, +}) { + if (testRunCommandOverride != null) { + final result = testRunCommandOverride!(TestRunCommandArgs( + executable: executable, + arguments: arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stdoutEncoding: stdoutEncoding, + stderrEncoding: stderrEncoding, + )); + return ProcessResult( + result.pid, + result.exitCode, + result.stdout, + result.stderr, + ); + } + log.finer('Running command $executable ${arguments.join(' ')}'); + final res = Process.runSync( + _resolveExecutable(executable), + arguments, + workingDirectory: workingDirectory, + environment: environment, + includeParentEnvironment: includeParentEnvironment, + runInShell: runInShell, + stderrEncoding: stderrEncoding, + stdoutEncoding: stdoutEncoding, + ); + if (res.exitCode != 0) { + throw CommandFailedException( + executable: executable, + arguments: arguments, + result: res, + ); + } else { + return res; + } +} + +class RustupNotFoundException implements Exception { + @override + String toString() { + return [ + ' ', + 'rustup not found in PATH.', + ' ', + 'Maybe you need to install Rust? It only takes a minute:', + ' ', + if (Platform.isWindows) 'https://www.rust-lang.org/tools/install', + if (hasHomebrewRustInPath()) ...[ + '\$ brew unlink rust # Unlink homebrew Rust from PATH', + ], + if (!Platform.isWindows) + "\$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh", + ' ', + ].join('\n'); + } + + static bool hasHomebrewRustInPath() { + if (!Platform.isMacOS) { + return false; + } + final envPath = Platform.environment['PATH'] ?? ''; + final paths = envPath.split(':'); + return paths.any((p) { + return p.contains('homebrew') && File(path.join(p, 'rustc')).existsSync(); + }); + } +} + +String _resolveExecutable(String executable) { + if (executable == 'rustup') { + final resolved = Rustup.executablePath(); + if (resolved != null) { + return resolved; + } + throw RustupNotFoundException(); + } else { + return executable; + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart b/webf/example/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart new file mode 100644 index 0000000000..0094c644a6 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/lib/src/verify_binaries.dart @@ -0,0 +1,81 @@ +import 'dart:io'; + +import 'package:ed25519_edwards/ed25519_edwards.dart'; +import 'package:http/http.dart'; + +import 'artifacts_provider.dart'; +import 'cargo.dart'; +import 'crate_hash.dart'; +import 'options.dart'; +import 'precompile_binaries.dart'; +import 'target.dart'; + +class VerifyBinaries { + VerifyBinaries({ + required this.manifestDir, + }); + + final String manifestDir; + + Future run() async { + final crateInfo = CrateInfo.load(manifestDir); + + final config = CargokitCrateOptions.load(manifestDir: manifestDir); + final precompiledBinaries = config.precompiledBinaries; + if (precompiledBinaries == null) { + stdout.writeln('Crate does not support precompiled binaries.'); + } else { + final crateHash = CrateHash.compute(manifestDir); + stdout.writeln('Crate hash: $crateHash'); + + for (final target in Target.all) { + final message = 'Checking ${target.rust}...'; + stdout.write(message.padRight(40)); + stdout.flush(); + + final artifacts = getArtifactNames( + target: target, + libraryName: crateInfo.packageName, + remote: true, + ); + + final prefix = precompiledBinaries.uriPrefix; + + bool ok = true; + + for (final artifact in artifacts) { + final fileName = PrecompileBinaries.fileName(target, artifact); + final signatureFileName = + PrecompileBinaries.signatureFileName(target, artifact); + + final url = Uri.parse('$prefix$crateHash/$fileName'); + final signatureUrl = + Uri.parse('$prefix$crateHash/$signatureFileName'); + + final signature = await get(signatureUrl); + if (signature.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + final asset = await get(url); + if (asset.statusCode != 200) { + stdout.writeln('MISSING'); + ok = false; + break; + } + + if (!verify(precompiledBinaries.publicKey, asset.bodyBytes, + signature.bodyBytes)) { + stdout.writeln('INVALID SIGNATURE'); + ok = false; + } + } + + if (ok) { + stdout.writeln('OK'); + } + } + } + } +} diff --git a/webf/example/rust_builder/cargokit/build_tool/pubspec.lock b/webf/example/rust_builder/cargokit/build_tool/pubspec.lock new file mode 100644 index 0000000000..343bdd3694 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/pubspec.lock @@ -0,0 +1,453 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 + url: "https://pub.dev" + source: hosted + version: "64.0.0" + adaptive_number: + dependency: transitive + description: + name: adaptive_number + sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" + url: "https://pub.dev" + source: hosted + version: "6.2.0" + args: + dependency: "direct main" + description: + name: args + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + collection: + dependency: "direct main" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: "direct main" + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + coverage: + dependency: transitive + description: + name: coverage + sha256: "2fb815080e44a09b85e0f2ca8a820b15053982b2e714b59267719e8a9ff17097" + url: "https://pub.dev" + source: hosted + version: "1.6.3" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + ed25519_edwards: + dependency: "direct main" + description: + name: ed25519_edwards + sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + file: + dependency: transitive + description: + name: file + sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d" + url: "https://pub.dev" + source: hosted + version: "6.1.4" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + github: + dependency: "direct main" + description: + name: github + sha256: "9966bc13bf612342e916b0a343e95e5f046c88f602a14476440e9b75d2295411" + url: "https://pub.dev" + source: hosted + version: "9.17.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + hex: + dependency: "direct main" + description: + name: hex + sha256: "4e7cd54e4b59ba026432a6be2dd9d96e4c5205725194997193bf871703b82c4a" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + http: + dependency: "direct main" + description: + name: http + sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + io: + dependency: transitive + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: transitive + description: + name: js + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + url: "https://pub.dev" + source: hosted + version: "0.6.7" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: b10a7b2ff83d83c777edba3c6a0f97045ddadd56c944e1a23a3fdf43a1bf4467 + url: "https://pub.dev" + source: hosted + version: "4.8.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + logging: + dependency: "direct main" + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + url: "https://pub.dev" + source: hosted + version: "0.12.16" + meta: + dependency: transitive + description: + name: meta + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + mime: + dependency: transitive + description: + name: mime + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e + url: "https://pub.dev" + source: hosted + version: "1.0.4" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: "direct main" + description: + name: path + sha256: "2ad4cddff7f5cc0e2d13069f2a3f7a73ca18f66abd6f5ecf215219cdb3638edb" + url: "https://pub.dev" + source: hosted + version: "1.8.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 + url: "https://pub.dev" + source: hosted + version: "5.4.0" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e + url: "https://pub.dev" + source: hosted + version: "1.1.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" + url: "https://pub.dev" + source: hosted + version: "0.10.12" + source_span: + dependency: "direct main" + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test: + dependency: "direct dev" + description: + name: test + sha256: "9b0dd8e36af4a5b1569029949d50a52cb2a2a2fdaa20cebb96e6603b9ae241f9" + url: "https://pub.dev" + source: hosted + version: "1.24.6" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + test_core: + dependency: transitive + description: + name: test_core + sha256: "4bef837e56375537055fdbbbf6dd458b1859881f4c7e6da936158f77d61ab265" + url: "https://pub.dev" + source: hosted + version: "0.5.6" + toml: + dependency: "direct main" + description: + name: toml + sha256: "157c5dca5160fced243f3ce984117f729c788bb5e475504f3dbcda881accee44" + url: "https://pub.dev" + source: hosted + version: "0.14.0" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + version: + dependency: "direct main" + description: + name: version + sha256: "2307e23a45b43f96469eeab946208ed63293e8afca9c28cd8b5241ff31c55f55" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0fae432c85c4ea880b33b497d32824b97795b04cdaa74d270219572a1f50268d" + url: "https://pub.dev" + source: hosted + version: "11.9.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b + url: "https://pub.dev" + source: hosted + version: "2.4.0" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "67d3a8b6c79e1987d19d848b0892e582dbb0c66c57cc1fef58a177dd2aa2823d" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + yaml: + dependency: "direct main" + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.0.0 <4.0.0" diff --git a/webf/example/rust_builder/cargokit/build_tool/pubspec.yaml b/webf/example/rust_builder/cargokit/build_tool/pubspec.yaml new file mode 100644 index 0000000000..e01aa0ae6d --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/pubspec.yaml @@ -0,0 +1,30 @@ +name: build_tool +description: Cargokit build_tool. Facilitates the build of Rust crate during Flutter application build. +publish_to: none +version: 1.0.0 + +environment: + sdk: ">=3.0.0 <4.0.0" + +# Add regular dependencies here. +dependencies: + # these are pinned on purpose because the bundle_tool_runner doesn't have + # pubspec.lock. See run_build_tool.sh + logging: 1.2.0 + path: 1.8.0 + version: 3.0.0 + collection: 1.18.0 + ed25519_edwards: 0.3.1 + hex: 0.2.0 + yaml: 3.1.2 + source_span: 1.10.0 + github: 9.17.0 + args: 2.4.2 + crypto: 3.0.3 + convert: 3.1.1 + http: 1.1.0 + toml: 0.14.0 + +dev_dependencies: + lints: ^2.1.0 + test: ^1.24.0 diff --git a/webf/example/rust_builder/cargokit/build_tool/test/builder_test.dart b/webf/example/rust_builder/cargokit/build_tool/test/builder_test.dart new file mode 100644 index 0000000000..e92852e5fc --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/test/builder_test.dart @@ -0,0 +1,28 @@ +import 'package:build_tool/src/builder.dart'; +import 'package:test/test.dart'; + +void main() { + test('parseBuildConfiguration', () { + var b = BuildEnvironment.parseBuildConfiguration('debug'); + expect(b, BuildConfiguration.debug); + + b = BuildEnvironment.parseBuildConfiguration('profile'); + expect(b, BuildConfiguration.profile); + + b = BuildEnvironment.parseBuildConfiguration('release'); + expect(b, BuildConfiguration.release); + + b = BuildEnvironment.parseBuildConfiguration('debug-dev'); + expect(b, BuildConfiguration.debug); + + b = BuildEnvironment.parseBuildConfiguration('profile'); + expect(b, BuildConfiguration.profile); + + b = BuildEnvironment.parseBuildConfiguration('profile-prod'); + expect(b, BuildConfiguration.profile); + + // fallback to release + b = BuildEnvironment.parseBuildConfiguration('unknown'); + expect(b, BuildConfiguration.release); + }); +} diff --git a/webf/example/rust_builder/cargokit/build_tool/test/cargo_test.dart b/webf/example/rust_builder/cargokit/build_tool/test/cargo_test.dart new file mode 100644 index 0000000000..00afe29fb8 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/test/cargo_test.dart @@ -0,0 +1,28 @@ +import 'package:build_tool/src/cargo.dart'; +import 'package:test/test.dart'; + +final _cargoToml = """ +[workspace] + +[profile.release] +lto = true +panic = "abort" +opt-level = "z" +# strip = "symbols" + +[package] +name = "super_native_extensions" +version = "0.1.0" +edition = "2021" +resolver = "2" + +[lib] +crate-type = ["cdylib", "staticlib"] +"""; + +void main() { + test('parseCargoToml', () { + final info = CrateInfo.parseManifest(_cargoToml); + expect(info.packageName, 'super_native_extensions'); + }); +} diff --git a/webf/example/rust_builder/cargokit/build_tool/test/options_test.dart b/webf/example/rust_builder/cargokit/build_tool/test/options_test.dart new file mode 100644 index 0000000000..25a85b6a79 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/test/options_test.dart @@ -0,0 +1,75 @@ +import 'package:build_tool/src/builder.dart'; +import 'package:build_tool/src/options.dart'; +import 'package:hex/hex.dart'; +import 'package:test/test.dart'; +import 'package:yaml/yaml.dart'; + +void main() { + test('parseCargoBuildOptions', () { + final yaml = """ +toolchain: nightly +extra_flags: + - -Z + # Comment here + - build-std=panic_abort,std +"""; + final node = loadYamlNode(yaml); + final options = CargoBuildOptions.parse(node); + expect(options.toolchain, Toolchain.nightly); + expect(options.flags, ['-Z', 'build-std=panic_abort,std']); + }); + + test('parsePrecompiledBinaries', () { + final yaml = """ +url_prefix: https://url-prefix +public_key: a4c3433798eb2c36edf2b94dbb4dd899d57496ca373a8982d8a792410b7f6445 +"""; + final precompiledBinaries = PrecompiledBinaries.parse(loadYamlNode(yaml)); + final key = HEX.decode( + 'a4c3433798eb2c36edf2b94dbb4dd899d57496ca373a8982d8a792410b7f6445'); + expect(precompiledBinaries.uriPrefix, 'https://url-prefix'); + expect(precompiledBinaries.publicKey.bytes, key); + }); + + test('parseCargokitOptions', () { + const yaml = ''' +cargo: + # For smalles binaries rebuilt the standard library with panic=abort + debug: + toolchain: nightly + extra_flags: + - -Z + # Comment here + - build-std=panic_abort,std + release: + toolchain: beta + +precompiled_binaries: + url_prefix: https://url-prefix + public_key: a4c3433798eb2c36edf2b94dbb4dd899d57496ca373a8982d8a792410b7f6445 +'''; + final options = CargokitCrateOptions.parse(loadYamlNode(yaml)); + expect(options.precompiledBinaries?.uriPrefix, 'https://url-prefix'); + final key = HEX.decode( + 'a4c3433798eb2c36edf2b94dbb4dd899d57496ca373a8982d8a792410b7f6445'); + expect(options.precompiledBinaries?.publicKey.bytes, key); + + final debugOptions = options.cargo[BuildConfiguration.debug]!; + expect(debugOptions.toolchain, Toolchain.nightly); + expect(debugOptions.flags, ['-Z', 'build-std=panic_abort,std']); + + final releaseOptions = options.cargo[BuildConfiguration.release]!; + expect(releaseOptions.toolchain, Toolchain.beta); + expect(releaseOptions.flags, []); + }); + + test('parseCargokitUserOptions', () { + const yaml = ''' +use_precompiled_binaries: false +verbose_logging: true +'''; + final options = CargokitUserOptions.parse(loadYamlNode(yaml)); + expect(options.usePrecompiledBinaries, false); + expect(options.verboseLogging, true); + }); +} diff --git a/webf/example/rust_builder/cargokit/build_tool/test/rustup_test.dart b/webf/example/rust_builder/cargokit/build_tool/test/rustup_test.dart new file mode 100644 index 0000000000..af95303c35 --- /dev/null +++ b/webf/example/rust_builder/cargokit/build_tool/test/rustup_test.dart @@ -0,0 +1,66 @@ +import 'package:build_tool/src/rustup.dart'; +import 'package:build_tool/src/util.dart'; +import 'package:test/test.dart'; + +void main() { + test('rustup with no toolchains', () { + bool didListToolchains = false; + bool didInstallStable = false; + bool didListTargets = false; + testRunCommandOverride = (args) { + expect(args.executable, 'rustup'); + switch (args.arguments) { + case ['toolchain', 'list']: + didListToolchains = true; + return TestRunCommandResult(stdout: 'no installed toolchains\n'); + case ['toolchain', 'install', 'stable']: + didInstallStable = true; + return TestRunCommandResult(); + case ['target', 'list', '--toolchain', 'stable', '--installed']: + didListTargets = true; + return TestRunCommandResult( + stdout: 'x86_64-unknown-linux-gnu\nx86_64-apple-darwin\n'); + default: + throw Exception('Unexpected call: ${args.arguments}'); + } + }; + final rustup = Rustup(); + rustup.installToolchain('stable'); + expect(didInstallStable, true); + expect(didListToolchains, true); + expect(didListTargets, true); + expect(rustup.installedTargets('stable'), [ + 'x86_64-unknown-linux-gnu', + 'x86_64-apple-darwin', + ]); + testRunCommandOverride = null; + }); + + test('rustup with esp toolchain', () { + final targetsQueried = []; + testRunCommandOverride = (args) { + expect(args.executable, 'rustup'); + switch (args.arguments) { + case ['toolchain', 'list']: + return TestRunCommandResult( + stdout: 'stable-aarch64-apple-darwin (default)\n' + 'nightly-aarch64-apple-darwin\n' + 'esp\n'); + case ['target', 'list', '--toolchain', String toolchain, '--installed']: + targetsQueried.add(toolchain); + return TestRunCommandResult(stdout: '$toolchain:target\n'); + default: + throw Exception('Unexpected call: ${args.arguments}'); + } + }; + final rustup = Rustup(); + expect(targetsQueried, [ + 'stable-aarch64-apple-darwin', + 'nightly-aarch64-apple-darwin', + ]); + expect(rustup.installedTargets('stable'), + ['stable-aarch64-apple-darwin:target']); + expect(rustup.installedTargets('nightly'), + ['nightly-aarch64-apple-darwin:target']); + }); +} diff --git a/webf/example/rust_builder/cargokit/cmake/cargokit.cmake b/webf/example/rust_builder/cargokit/cmake/cargokit.cmake new file mode 100644 index 0000000000..ddd05df9b4 --- /dev/null +++ b/webf/example/rust_builder/cargokit/cmake/cargokit.cmake @@ -0,0 +1,99 @@ +SET(cargokit_cmake_root "${CMAKE_CURRENT_LIST_DIR}/..") + +# Workaround for https://github.com/dart-lang/pub/issues/4010 +get_filename_component(cargokit_cmake_root "${cargokit_cmake_root}" REALPATH) + +if(WIN32) + # REALPATH does not properly resolve symlinks on windows :-/ + execute_process(COMMAND powershell -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_LIST_DIR}/resolve_symlinks.ps1" "${cargokit_cmake_root}" OUTPUT_VARIABLE cargokit_cmake_root OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() + +# Arguments +# - target: CMAKE target to which rust library is linked +# - manifest_dir: relative path from current folder to directory containing cargo manifest +# - lib_name: cargo package name +# - any_symbol_name: name of any exported symbol from the library. +# used on windows to force linking with library. +function(apply_cargokit target manifest_dir lib_name any_symbol_name) + + set(CARGOKIT_LIB_NAME "${lib_name}") + set(CARGOKIT_LIB_FULL_NAME "${CMAKE_SHARED_MODULE_PREFIX}${CARGOKIT_LIB_NAME}${CMAKE_SHARED_MODULE_SUFFIX}") + if (CMAKE_CONFIGURATION_TYPES) + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/$/${CARGOKIT_LIB_FULL_NAME}") + else() + set(CARGOKIT_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") + set(OUTPUT_LIB "${CMAKE_CURRENT_BINARY_DIR}/${CARGOKIT_LIB_FULL_NAME}") + endif() + set(CARGOKIT_TEMP_DIR "${CMAKE_CURRENT_BINARY_DIR}/cargokit_build") + + if (FLUTTER_TARGET_PLATFORM) + set(CARGOKIT_TARGET_PLATFORM "${FLUTTER_TARGET_PLATFORM}") + else() + set(CARGOKIT_TARGET_PLATFORM "windows-x64") + endif() + + set(CARGOKIT_ENV + "CARGOKIT_CMAKE=${CMAKE_COMMAND}" + "CARGOKIT_CONFIGURATION=$" + "CARGOKIT_MANIFEST_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${manifest_dir}" + "CARGOKIT_TARGET_TEMP_DIR=${CARGOKIT_TEMP_DIR}" + "CARGOKIT_OUTPUT_DIR=${CARGOKIT_OUTPUT_DIR}" + "CARGOKIT_TARGET_PLATFORM=${CARGOKIT_TARGET_PLATFORM}" + "CARGOKIT_TOOL_TEMP_DIR=${CARGOKIT_TEMP_DIR}/tool" + "CARGOKIT_ROOT_PROJECT_DIR=${CMAKE_SOURCE_DIR}" + ) + + if (WIN32) + set(SCRIPT_EXTENSION ".cmd") + set(IMPORT_LIB_EXTENSION ".lib") + else() + set(SCRIPT_EXTENSION ".sh") + set(IMPORT_LIB_EXTENSION "") + execute_process(COMMAND chmod +x "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}") + endif() + + # Using generators in custom command is only supported in CMake 3.20+ + if (CMAKE_CONFIGURATION_TYPES AND ${CMAKE_VERSION} VERSION_LESS "3.20.0") + foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES) + add_custom_command( + OUTPUT + "${CMAKE_CURRENT_BINARY_DIR}/${CONFIG}/${CARGOKIT_LIB_FULL_NAME}" + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endforeach() + else() + add_custom_command( + OUTPUT + ${OUTPUT_LIB} + "${CMAKE_CURRENT_BINARY_DIR}/_phony_" + COMMAND ${CMAKE_COMMAND} -E env ${CARGOKIT_ENV} + "${cargokit_cmake_root}/run_build_tool${SCRIPT_EXTENSION}" build-cmake + VERBATIM + ) + endif() + + + set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/_phony_" PROPERTIES SYMBOLIC TRUE) + + if (TARGET ${target}) + # If we have actual cmake target provided create target and make existing + # target depend on it + add_custom_target("${target}_cargokit" DEPENDS ${OUTPUT_LIB}) + add_dependencies("${target}" "${target}_cargokit") + target_link_libraries("${target}" PRIVATE "${OUTPUT_LIB}${IMPORT_LIB_EXTENSION}") + if(WIN32) + target_link_options(${target} PRIVATE "/INCLUDE:${any_symbol_name}") + endif() + else() + # Otherwise (FFI) just use ALL to force building always + add_custom_target("${target}_cargokit" ALL DEPENDS ${OUTPUT_LIB}) + endif() + + # Allow adding the output library to plugin bundled libraries + set("${target}_cargokit_lib" ${OUTPUT_LIB} PARENT_SCOPE) + +endfunction() diff --git a/webf/example/rust_builder/cargokit/cmake/resolve_symlinks.ps1 b/webf/example/rust_builder/cargokit/cmake/resolve_symlinks.ps1 new file mode 100644 index 0000000000..3d10d283c2 --- /dev/null +++ b/webf/example/rust_builder/cargokit/cmake/resolve_symlinks.ps1 @@ -0,0 +1,27 @@ +function Resolve-Symlinks { + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [string] $Path + ) + + [string] $separator = '/' + [string[]] $parts = $Path.Split($separator) + + [string] $realPath = '' + foreach ($part in $parts) { + if ($realPath -and !$realPath.EndsWith($separator)) { + $realPath += $separator + } + $realPath += $part + $item = Get-Item $realPath + if ($item.Target) { + $realPath = $item.Target.Replace('\', '/') + } + } + $realPath +} + +$path=Resolve-Symlinks -Path $args[0] +Write-Host $path diff --git a/webf/example/rust_builder/cargokit/docs/architecture.md b/webf/example/rust_builder/cargokit/docs/architecture.md new file mode 100644 index 0000000000..d9bcf4e299 --- /dev/null +++ b/webf/example/rust_builder/cargokit/docs/architecture.md @@ -0,0 +1,104 @@ +# Cargokit Architecture + +Note: This is mostly relevant for plugins authors that want to see a bit under the hood rather then just following a tutorial. + +In ideal conditions the end-developer using the plugin should not even be aware of Cargokit existence. + +## Integration + +Cargokit is meant to be included in Flutter plugin (or application) that contains the Rust crate to be built during the Flutter build process. + +Cargokit can be either incuded as git submodule or git subtree (required for plugins - as pub does not support submodules for git dependencies). + +For a step by step tutorial on integrating Cargokit with a Flutter plugin see https://matejknopp.com/post/flutter_plugin_in_rust_with_no_prebuilt_binaries/. + +## build_tool + +Build tool is the core of cargokit. It is a Dart command line package that facilitates the build of Rust crate. It is invoked during the Flutter build process to build (or download) Rust artifacts, but it can be also used as a standalone tool. + +It handles the following commands: + +### build-cmake + +This is invoked from `cargokit.cmake` and it is used to build the Rust crate into a dynamic library on Linux and Windows (which use CMake as build system). + +The command takes no additional arguments, everything is controlled during environment variables set by `cargokit.cmake`. + +### build-gradle + +This is invoked from `plugin.gradle` and it is used to build the Rust crate into a dynamic library on Android. The command takes no additional arguments, everything is controlled during environment variables set by `plugin.gradle`. + +The build_tool installs NDK if needed, configures the Rust environment for cross compilation and then invokes `cargo build` with appropriate arguments and environment variables. + +The build-tool also acts a linker driver. + +### build-pod + +This is invoked from plugin's podspec `script_phase` through `build_pod.sh`. Bundle tool will build the Rust crate into a static library that gets linked into the plugin Framework. In this case must have `:execution_position` set to `:before_compile`. + +Cargokit will build binaries for all active architectures from XCode build and lipo them togherer. + +When using Cargokit to integrate Rust code with an application (not a plugin) you can also configure the `Cargo.toml` to just build a dynamic library. When Cargokit finds that the crate only built a dylib and no static lib, it will attempt to replace the Cocoapod framework binary with the dylib. In this case the script `:execution_position` must be set to `:after_compile`. This is *not* recommended for plugins and it's quite experimental. + +### gen-key, precompile-binaries, verify-binaries + +These are used as when providing precompiled binaries for Plugin. See [precompiled_binaries.md](precompiled_binaries.md) for more information. + +## Launching the build_tool during build. + +During Flutter build, the build tool can not be launched directly using `dart run`. Rather it is launched through `run_build_tool.sh` and `run_build_tool.cmd`. Because the `build_tool` is shipped as part of plugin, we generally don't want to write into the plugin directory during build, which would happen if the `build_tool` was simply invoked through `dart run` (For example the `.dart_tool/package_config.json` file would get written inside the `build_tool` directory). + +Instead the `run_build_tool` script creates a minimal Dart command line package in the build directory and references the `build_tool` as package. That way the `.dart_tool/package_config.json` file is created in the temporary build folder and not in the plugin itself. The script also precompiles the Dart code to speed up subsequent invocations. + +## Configuring Cargokit + +### Configuration for the Rust crate + +Cargokit can be configured through a `cargokit.yaml` file, which can be used to control the build of the Rust package and is placed into the Rust crate next to `Cargo.toml`. + +Here is an example `cargokit.yaml` with comments: +```yaml +cargo: + debug: # Configuration of cargo execution during debug builds + toolchain: stable # default + release: # Configuration of cargo execution for release builds + toolchain: nightly # rustup will be invoked with nightly toolchain + extra_flags: # extra arguments passed to cargo build + - -Z + - build-std=panic_abort,std + +# If crate ships with precompiled binaries, they can be configured here. +precompiled_binaries: + # Uri prefix used when downloading precompiled binaries. + url_prefix: https://github.com/superlistapp/super_native_extensions/releases/download/precompiled_ + + # Public key for verifying downloaded precompiled binaries. + public_key: 3a257ef1c7d72d84225ac4658d24812ada50a7a7a8a2138c2a91353389fdc514 +``` + +### Configuration for the application consuming the plugin + +A `cargokit_options.yaml` file can also be placed by developer using plugin to the root of the application package. In which case the file can be used to specify following options: + +```yaml +# Enables verbose logging of Cargokit during build +verbose_logging: true + +# Opts out of using precompiled binaries. If crate has configured +# and deployed precompiled binaries, these will be by default used whenever Rustup +# is not installed. With `use_precompiled_binaries` set to false, the build will +# instead be aborted prompting user to install Rustup. +use_precompiled_binaries: false +``` + +## Detecting Rustup + +When the plugin doesn't come with precompiled libraries (or user opt-out), `build_tool` will need to invoke Rustup during build to ensure that required Rust targets and toolchain are installed for current build and to build the Rust crate. + +Cargokit will attempt to detect Rustup in the default Rustup installation location (`~/.cargo/rustup`) as well as in PATH. This is done so that if user install Rustup but doesn't properly configure PATH, Cargokit will still work. + +If `build_tool` doesn't find Rustup, it will about the build with a message showing instructions to install Rustup specific to current platform. + +On macOS it will also detect a homebrew Rust installation in PATH and will prompt user to call `brew unlink rust` first to remove homebrew Rust installation from PATH, because it may interfere with Rustup. + +Homebrew Rust installation can not be used by Cargokit, because it can only build for host platform. Cargokit needs to be able to cross compile the Rust crate for iOS and Android and thus needs full Rustup installation. diff --git a/webf/example/rust_builder/cargokit/docs/precompiled_binaries.md b/webf/example/rust_builder/cargokit/docs/precompiled_binaries.md new file mode 100644 index 0000000000..2026e8677c --- /dev/null +++ b/webf/example/rust_builder/cargokit/docs/precompiled_binaries.md @@ -0,0 +1,95 @@ +# Precompiled Binaries + +Because Cargokit builds the Rust crate during Flutter build, it is inherently +dependend on the Rust toolchain being installed on the developer's machine. + +To decrease the friction, it is possible for Cargokit to use precompiled binaries instead. + +This is how the process of using precompiled binaries looks from the perspective of the build on developer machine: + +1. Cargokit checks if there is `cargokit_options.yaml` file in the root folder of target application. If there is one, it will be checked for `use_precompiled_binaries` options to see if user opted out of using precompiled binaries. In which case Cargokit will insist on building from source. Cargokit will also build from source if the configuration file is absent, but user has Rustup installed. + +2. Cargokit checks if there is `cargokit.yaml` file placed in the Rust crate. If there is one, it will be checked for `precompiled_binaries` section to see if crate supports precompiled binaries. The configuration section must contain a public key and URL prefix. + +3. Cargokit computes a `crate-hash`. This is a SHA256 hash value computed from all Rust files inside crate, `Cargo.toml`, `Cargo.lock` and `cargokit.yaml`. This uniquely identifies the crate and it is used to find the correct precompiled binaries. + +4. Cargokit will attempt to download the precompiled binaries for target platform and `crate_hash` combination and a signature file for each downloaded binary. If download succeeds, the binary content will be verified against the signature and public key included in `cargokit.yaml` (which is part of Rust crate and thus part of published Flutter package). + +5. If the verification succeeds, the precompiled binaries will be used. Otherwise the binary will be discarded and Cargokit will insist on building from source. + +## Providing precompiled binaries + +Note that this assumes that precompiled binaries will be generated during github actions and deployed as github releases. + +### Use `build_tool` to generate a key-pair: + +``` +dart run build_tool gen-key +``` + +This will print the private key and public key. Store the private key securely. It needs to be provided as a secret to github action. + +The public key should be included in `cargokit.yaml` file in the Rust crate. + +### Provide a `cargokit.yaml` file in the Rust crate + +The file must be placed alongside Cargo.toml. + +```yaml +precompiled_binaries: + # Uri prefix used when downloading precompiled binaries. + url_prefix: https://github.com///releases/download/precompiled_ + + # Public key for verifying downloaded precompiled binaries. + public_key: +``` + +### Configure a github action to build and upload precompiled binaries. + +The github action should be run at every commit to main branch (and possibly other branches). + +The action needs two secrets - private key for signing binaries and GitHub token for uploading binaries as releases. Here is example action that precompiles and uploads binaries for all supported targets. + +```yaml +on: + push: + branches: [ main ] + +name: Precompile Binaries + +jobs: + Precompile: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - macOS-latest + - windows-latest + steps: + - uses: actions/checkout@v2 + - uses: dart-lang/setup-dart@v1 + - name: Install GTK + if: (matrix.os == 'ubuntu-latest') + run: sudo apt-get update && sudo apt-get install libgtk-3-dev + - name: Precompile + if: (matrix.os == 'macOS-latest') || (matrix.os == 'windows-latest') + run: dart run build_tool precompile-binaries -v --manifest-dir=../../rust --repository=superlistapp/super_native_extensions + working-directory: super_native_extensions/cargokit/build_tool + env: + GITHUB_TOKEN: ${{ secrets.RELEASE_GITHUB_TOKEN }} + PRIVATE_KEY: ${{ secrets.RELEASE_PRIVATE_KEY }} + - name: Precompile (with Android) + if: (matrix.os == 'ubuntu-latest') + run: dart run build_tool precompile-binaries -v --manifest-dir=../../rust --repository=superlistapp/super_native_extensions --android-sdk-location=/usr/local/lib/android/sdk --android-ndk-version=24.0.8215888 --android-min-sdk-version=23 + working-directory: super_native_extensions/cargokit/build_tool + env: + GITHUB_TOKEN: ${{ secrets.RELEASE_GITHUB_TOKEN }} + PRIVATE_KEY: ${{ secrets.RELEASE_PRIVATE_KEY }} +``` + +By default the `built_tool precompile-binaries` commands build and uploads the binaries for all targets buildable from current host. This can be overriden using the `--target ` argument. + +Android binaries will be built when `--android-sdk-location` and `--android-ndk-version` arguments are provided. + diff --git a/webf/example/rust_builder/cargokit/gradle/plugin.gradle b/webf/example/rust_builder/cargokit/gradle/plugin.gradle new file mode 100644 index 0000000000..37dd086af3 --- /dev/null +++ b/webf/example/rust_builder/cargokit/gradle/plugin.gradle @@ -0,0 +1,176 @@ +import java.nio.file.Paths +import org.apache.tools.ant.taskdefs.condition.Os + +CargoKitPlugin.file = buildscript.sourceFile + +apply plugin: CargoKitPlugin + +class CargoKitExtension { + String manifestDir; // Relative path to folder containing Cargo.toml + String libname; // Library name within Cargo.toml. Must be a cdylib +} + +abstract class CargoKitBuildTask extends DefaultTask { + + @Input + String buildMode + + @Input + String buildDir + + @Input + String outputDir + + @Input + String ndkVersion + + @Input + String sdkDirectory + + @Input + int compileSdkVersion; + + @Input + int minSdkVersion; + + @Input + String pluginFile + + @Input + List targetPlatforms + + @TaskAction + def build() { + if (project.cargokit.manifestDir == null) { + throw new GradleException("Property 'manifestDir' must be set on cargokit extension"); + } + + if (project.cargokit.libname == null) { + throw new GradleException("Property 'libname' must be set on cargokit extension"); + } + + def executableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "run_build_tool.cmd" : "run_build_tool.sh" + def path = Paths.get(new File(pluginFile).parent, "..", executableName); + + def manifestDir = Paths.get(project.buildscript.sourceFile.parent, project.cargokit.manifestDir) + + def rootProjectDir = project.rootProject.projectDir + + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + project.exec { + commandLine 'chmod', '+x', path + } + } + + project.exec { + executable path + args "build-gradle" + environment "CARGOKIT_ROOT_PROJECT_DIR", rootProjectDir + environment "CARGOKIT_TOOL_TEMP_DIR", "${buildDir}/build_tool" + environment "CARGOKIT_MANIFEST_DIR", manifestDir + environment "CARGOKIT_CONFIGURATION", buildMode + environment "CARGOKIT_TARGET_TEMP_DIR", buildDir + environment "CARGOKIT_OUTPUT_DIR", outputDir + environment "CARGOKIT_NDK_VERSION", ndkVersion + environment "CARGOKIT_SDK_DIR", sdkDirectory + environment "CARGOKIT_COMPILE_SDK_VERSION", compileSdkVersion + environment "CARGOKIT_MIN_SDK_VERSION", minSdkVersion + environment "CARGOKIT_TARGET_PLATFORMS", targetPlatforms.join(",") + environment "CARGOKIT_JAVA_HOME", System.properties['java.home'] + } + } +} + +class CargoKitPlugin implements Plugin { + + static String file; + + private Plugin findFlutterPlugin(Project rootProject) { + _findFlutterPlugin(rootProject.childProjects) + } + + private Plugin _findFlutterPlugin(Map projects) { + for (project in projects) { + for (plugin in project.value.getPlugins()) { + if (plugin.class.name == "FlutterPlugin") { + return plugin; + } + } + def plugin = _findFlutterPlugin(project.value.childProjects); + if (plugin != null) { + return plugin; + } + } + return null; + } + + @Override + void apply(Project project) { + def plugin = findFlutterPlugin(project.rootProject); + + project.extensions.create("cargokit", CargoKitExtension) + + if (plugin == null) { + print("Flutter plugin not found, CargoKit plugin will not be applied.") + return; + } + + def cargoBuildDir = "${project.buildDir}/build" + + // Determine if the project is an application or library + def isApplication = plugin.project.plugins.hasPlugin('com.android.application') + def variants = isApplication ? plugin.project.android.applicationVariants : plugin.project.android.libraryVariants + + variants.all { variant -> + + final buildType = variant.buildType.name + + def cargoOutputDir = "${project.buildDir}/jniLibs/${buildType}"; + def jniLibs = project.android.sourceSets.maybeCreate(buildType).jniLibs; + jniLibs.srcDir(new File(cargoOutputDir)) + + def platforms = plugin.getTargetPlatforms().collect() + + // Same thing addFlutterDependencies does in flutter.gradle + if (buildType == "debug") { + platforms.add("android-x86") + platforms.add("android-x64") + } + + // The task name depends on plugin properties, which are not available + // at this point + project.getGradle().afterProject { + def taskName = "cargokitCargoBuild${project.cargokit.libname.capitalize()}${buildType.capitalize()}"; + + if (project.tasks.findByName(taskName)) { + return + } + + if (plugin.project.android.ndkVersion == null) { + throw new GradleException("Please set 'android.ndkVersion' in 'app/build.gradle'.") + } + + def task = project.tasks.create(taskName, CargoKitBuildTask.class) { + buildMode = variant.buildType.name + buildDir = cargoBuildDir + outputDir = cargoOutputDir + ndkVersion = plugin.project.android.ndkVersion + sdkDirectory = plugin.project.android.sdkDirectory + minSdkVersion = plugin.project.android.defaultConfig.minSdkVersion.apiLevel as int + compileSdkVersion = plugin.project.android.compileSdkVersion.substring(8) as int + targetPlatforms = platforms + pluginFile = CargoKitPlugin.file + } + def onTask = { newTask -> + if (newTask.name == "merge${buildType.capitalize()}NativeLibs") { + newTask.dependsOn task + // Fix gradle 7.4.2 not picking up JNI library changes + newTask.outputs.upToDateWhen { false } + } + } + project.tasks.each onTask + project.tasks.whenTaskAdded onTask + } + } + } +} diff --git a/webf/example/rust_builder/cargokit/run_build_tool.cmd b/webf/example/rust_builder/cargokit/run_build_tool.cmd new file mode 100644 index 0000000000..c45d0aa8b5 --- /dev/null +++ b/webf/example/rust_builder/cargokit/run_build_tool.cmd @@ -0,0 +1,91 @@ +@echo off +setlocal + +setlocal ENABLEDELAYEDEXPANSION + +SET BASEDIR=%~dp0 + +if not exist "%CARGOKIT_TOOL_TEMP_DIR%" ( + mkdir "%CARGOKIT_TOOL_TEMP_DIR%" +) +cd /D "%CARGOKIT_TOOL_TEMP_DIR%" + +SET BUILD_TOOL_PKG_DIR=%BASEDIR%build_tool +SET DART=%FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart + +set BUILD_TOOL_PKG_DIR_POSIX=%BUILD_TOOL_PKG_DIR:\=/% + +( + echo name: build_tool_runner + echo version: 1.0.0 + echo publish_to: none + echo. + echo environment: + echo sdk: '^>=3.0.0 ^<4.0.0' + echo. + echo dependencies: + echo build_tool: + echo path: %BUILD_TOOL_PKG_DIR_POSIX% +) >pubspec.yaml + +if not exist bin ( + mkdir bin +) + +( + echo import 'package:build_tool/build_tool.dart' as build_tool; + echo void main^(List^ args^) ^{ + echo build_tool.runMain^(args^); + echo ^} +) >bin\build_tool_runner.dart + +SET PRECOMPILED=bin\build_tool_runner.dill + +REM To detect changes in package we compare output of DIR /s (recursive) +set PREV_PACKAGE_INFO=.dart_tool\package_info.prev +set CUR_PACKAGE_INFO=.dart_tool\package_info.cur + +DIR "%BUILD_TOOL_PKG_DIR%" /s > "%CUR_PACKAGE_INFO%_orig" + +REM Last line in dir output is free space on harddrive. That is bound to +REM change between invocation so we need to remove it +( + Set "Line=" + For /F "UseBackQ Delims=" %%A In ("%CUR_PACKAGE_INFO%_orig") Do ( + SetLocal EnableDelayedExpansion + If Defined Line Echo !Line! + EndLocal + Set "Line=%%A") +) >"%CUR_PACKAGE_INFO%" +DEL "%CUR_PACKAGE_INFO%_orig" + +REM Compare current directory listing with previous +FC /B "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" > nul 2>&1 + +If %ERRORLEVEL% neq 0 ( + REM Changed - copy current to previous and remove precompiled kernel + if exist "%PREV_PACKAGE_INFO%" ( + DEL "%PREV_PACKAGE_INFO%" + ) + MOVE /Y "%CUR_PACKAGE_INFO%" "%PREV_PACKAGE_INFO%" + if exist "%PRECOMPILED%" ( + DEL "%PRECOMPILED%" + ) +) + +REM There is no CUR_PACKAGE_INFO it was renamed in previous step to %PREV_PACKAGE_INFO% +REM which means we need to do pub get and precompile +if not exist "%PRECOMPILED%" ( + echo Running pub get in "%cd%" + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart +) + +"%DART%" "%PRECOMPILED%" %* + +REM 253 means invalid snapshot version. +If %ERRORLEVEL% equ 253 ( + "%DART%" pub get --no-precompile + "%DART%" compile kernel bin/build_tool_runner.dart + "%DART%" "%PRECOMPILED%" %* +) diff --git a/webf/example/rust_builder/cargokit/run_build_tool.sh b/webf/example/rust_builder/cargokit/run_build_tool.sh new file mode 100755 index 0000000000..6e594a23d4 --- /dev/null +++ b/webf/example/rust_builder/cargokit/run_build_tool.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash + +set -e + +BASEDIR=$(dirname "$0") + +mkdir -p "$CARGOKIT_TOOL_TEMP_DIR" + +cd "$CARGOKIT_TOOL_TEMP_DIR" + +# Write a very simple bin package in temp folder that depends on build_tool package +# from Cargokit. This is done to ensure that we don't pollute Cargokit folder +# with .dart_tool contents. + +BUILD_TOOL_PKG_DIR="$BASEDIR/build_tool" + +if [[ -z $FLUTTER_ROOT ]]; then # not defined + DART=dart +else + DART="$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart" +fi + +cat << EOF > "pubspec.yaml" +name: build_tool_runner +version: 1.0.0 +publish_to: none + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + build_tool: + path: "$BUILD_TOOL_PKG_DIR" +EOF + +mkdir -p "bin" + +cat << EOF > "bin/build_tool_runner.dart" +import 'package:build_tool/build_tool.dart' as build_tool; +void main(List args) { + build_tool.runMain(args); +} +EOF + +# Create alias for `shasum` if it does not exist and `sha1sum` exists +if ! [ -x "$(command -v shasum)" ] && [ -x "$(command -v sha1sum)" ]; then + shopt -s expand_aliases + alias shasum="sha1sum" +fi + +# Dart run will not cache any package that has a path dependency, which +# is the case for our build_tool_runner. So instead we precompile the package +# ourselves. +# To invalidate the cached kernel we use the hash of ls -LR of the build_tool +# package directory. This should be good enough, as the build_tool package +# itself is not meant to have any path dependencies. + +if [[ "$OSTYPE" == "darwin"* ]]; then + PACKAGE_HASH=$(ls -lTR "$BUILD_TOOL_PKG_DIR" | shasum) +else + PACKAGE_HASH=$(ls -lR --full-time "$BUILD_TOOL_PKG_DIR" | shasum) +fi + +PACKAGE_HASH_FILE=".package_hash" + +if [ -f "$PACKAGE_HASH_FILE" ]; then + EXISTING_HASH=$(cat "$PACKAGE_HASH_FILE") + if [ "$PACKAGE_HASH" != "$EXISTING_HASH" ]; then + rm "$PACKAGE_HASH_FILE" + fi +fi + +# Run pub get if needed. +if [ ! -f "$PACKAGE_HASH_FILE" ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + echo "$PACKAGE_HASH" > "$PACKAGE_HASH_FILE" +fi + +set +e + +"$DART" bin/build_tool_runner.dill "$@" + +exit_code=$? + +# 253 means invalid snapshot version. +if [ $exit_code == 253 ]; then + "$DART" pub get --no-precompile + "$DART" compile kernel bin/build_tool_runner.dart + "$DART" bin/build_tool_runner.dill "$@" + exit_code=$? +fi + +exit $exit_code diff --git a/webf/example/rust_builder/ios/Classes/dummy_file.c b/webf/example/rust_builder/ios/Classes/dummy_file.c new file mode 100644 index 0000000000..e06dab9968 --- /dev/null +++ b/webf/example/rust_builder/ios/Classes/dummy_file.c @@ -0,0 +1 @@ +// This is an empty file to force CocoaPods to create a framework. diff --git a/webf/example/rust_builder/ios/example_app.podspec b/webf/example/rust_builder/ios/example_app.podspec new file mode 100644 index 0000000000..071f29a767 --- /dev/null +++ b/webf/example/rust_builder/ios/example_app.podspec @@ -0,0 +1,45 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint example_app.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'example_app' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'Flutter' + s.platform = :ios, '11.0' + + # Flutter.framework does not contain a i386 slice. + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' + + s.script_phase = { + :name => 'Build Rust library', + # First argument is relative path to the `rust` folder, second is name of rust library + :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../rust example_app', + :execution_position => :before_compile, + :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'], + # Let XCode know that the static library referenced in -force_load below is + # created by this build step. + :output_files => ["${BUILT_PRODUCTS_DIR}/libexample_app.a"], + } + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + # Flutter.framework does not contain a i386 slice. + 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386', + 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/libexample_app.a', + } +end diff --git a/webf/example/rust_builder/linux/CMakeLists.txt b/webf/example/rust_builder/linux/CMakeLists.txt new file mode 100644 index 0000000000..e7e053d1bc --- /dev/null +++ b/webf/example/rust_builder/linux/CMakeLists.txt @@ -0,0 +1,26 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "example_app") +project(${PROJECT_NAME} LANGUAGES CXX) + + +# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> +# Replace add_subdirectory that references old C++ code with Cargokit: +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} ../rust example_app "") +# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(example_app_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + PARENT_SCOPE +) diff --git a/webf/example/rust_builder/macos/Classes/dummy_file.c b/webf/example/rust_builder/macos/Classes/dummy_file.c new file mode 100644 index 0000000000..e06dab9968 --- /dev/null +++ b/webf/example/rust_builder/macos/Classes/dummy_file.c @@ -0,0 +1 @@ +// This is an empty file to force CocoaPods to create a framework. diff --git a/webf/example/rust_builder/macos/example_app.podspec b/webf/example/rust_builder/macos/example_app.podspec new file mode 100644 index 0000000000..872d75cd7b --- /dev/null +++ b/webf/example/rust_builder/macos/example_app.podspec @@ -0,0 +1,44 @@ +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. +# Run `pod lib lint rust_lib_my_app.podspec` to validate before publishing. +# +Pod::Spec.new do |s| + s.name = 'example_app' + s.version = '0.0.1' + s.summary = 'A new Flutter FFI plugin project.' + s.description = <<-DESC +A new Flutter FFI plugin project. + DESC + s.homepage = 'http://example.com' + s.license = { :file => '../LICENSE' } + s.author = { 'Your Company' => 'email@example.com' } + + # This will ensure the source files in Classes/ are included in the native + # builds of apps using this FFI plugin. Podspec does not support relative + # paths, so Classes contains a forwarder C file that relatively imports + # `../src/*` so that the C sources can be shared among all target platforms. + s.source = { :path => '.' } + s.source_files = 'Classes/**/*' + s.dependency 'FlutterMacOS' + + s.platform = :osx, '10.11' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' + + s.script_phase = { + :name => 'Build Rust library', + # First argument is relative path to the `rust` folder, second is name of rust library + :script => 'sh "$PODS_TARGET_SRCROOT/../cargokit/build_pod.sh" ../rust example_app', + :execution_position => :before_compile, + :input_files => ['${BUILT_PRODUCTS_DIR}/cargokit_phony'], + # Let XCode know that the static library referenced in -force_load below is + # created by this build step. + :output_files => ["${BUILT_PRODUCTS_DIR}/libexample_app.a"], + } + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + # Flutter.framework does not contain a i386 slice. + 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386', + 'OTHER_LDFLAGS' => '-force_load ${BUILT_PRODUCTS_DIR}/libexample_app.a', + } +end diff --git a/webf/example/rust_builder/pubspec.yaml b/webf/example/rust_builder/pubspec.yaml new file mode 100644 index 0000000000..014d5ef0dc --- /dev/null +++ b/webf/example/rust_builder/pubspec.yaml @@ -0,0 +1,49 @@ +name: example_app +description: "A new Flutter FFI plugin project." +version: 0.0.1 +homepage: + +environment: + sdk: '>=3.3.1 <4.0.0' + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + ffi: ^2.1.0 + ffigen: ^9.0.1 + flutter_test: + sdk: flutter + flutter_lints: ^3.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) + # which should be registered in the plugin registry. This is required for + # using method channels. + # The Android 'package' specifies package in which the registered class is. + # This is required for using method channels on Android. + # The 'ffiPlugin' specifies that native code should be built and bundled. + # This is required for using `dart:ffi`. + # All these are used by the tooling to maintain consistency when + # adding or updating assets for this project. + # + # Please refer to README.md for a detailed explanation. + plugin: + platforms: + android: + ffiPlugin: true + ios: + ffiPlugin: true + linux: + ffiPlugin: true + macos: + ffiPlugin: true + windows: + ffiPlugin: true diff --git a/webf/example/rust_builder/rust/.gitignore b/webf/example/rust_builder/rust/.gitignore new file mode 100644 index 0000000000..58db1f31ef --- /dev/null +++ b/webf/example/rust_builder/rust/.gitignore @@ -0,0 +1,3 @@ +target +.idea +Cargo.lock diff --git a/webf/example/rust_builder/rust/Cargo.toml b/webf/example/rust_builder/rust/Cargo.toml new file mode 100644 index 0000000000..8307052055 --- /dev/null +++ b/webf/example/rust_builder/rust/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "example_app" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "staticlib"] + +[dependencies] +webf-sys = "0.16.0" + +[patch.crates-io] +webf-sys = { path = "../../../../bridge/rusty_webf_sys" } diff --git a/webf/example/rust_builder/rust/src/lib.rs b/webf/example/rust_builder/rust/src/lib.rs new file mode 100644 index 0000000000..898cbf86d7 --- /dev/null +++ b/webf/example/rust_builder/rust/src/lib.rs @@ -0,0 +1,82 @@ +use std::ffi::{c_void, CString}; +use webf_sys::event::Event; +use webf_sys::executing_context::ExecutingContextRustMethods; +use webf_sys::{AddEventListenerOptions, element, EventTargetMethods, initialize_webf_api, RustValue}; +use webf_sys::element::Element; +use webf_sys::node::NodeMethods; + +#[no_mangle] +pub extern "C" fn init_webf_app(handle: RustValue) -> *mut c_void { + let context = initialize_webf_api(handle); + println!("Context created"); + let exception_state = context.create_exception_state(); + let document = context.document(); + + let click_event = document.create_event("custom_click", &exception_state).unwrap(); + document.dispatch_event(&click_event, &exception_state); + + let div_element = document.create_element("div", &exception_state).unwrap(); + + let event_listener_options = AddEventListenerOptions { + passive: 0, + once: 0, + capture: 0, + }; + + let event_handler = Box::new(|event: &Event| { + let context = event.context(); + let exception_state = context.create_exception_state(); + let document = context.document(); + let div = document.create_element("div", &exception_state).unwrap(); + let text_node = document.create_text_node("Created By Event Handler", &exception_state).unwrap(); + div.append_child(&text_node.as_node(), &exception_state).unwrap(); + document.body().append_child(&div.as_node(), &exception_state).unwrap(); + }); + + div_element.add_event_listener("custom_click", event_handler.clone(), &event_listener_options, &exception_state).unwrap(); + + let real_click_handler = Box::new(move |event: &Event| { + let context = event.context(); + let exception_state = context.create_exception_state(); + let document = context.document(); + let custom_click_event = document.create_event("custom_click", &exception_state); + + match custom_click_event { + Ok(custom_click_event) => { + let event_target = event.target(); + let element: Element = event_target.as_element().unwrap(); + let _ = element.dispatch_event(&custom_click_event, &exception_state); + }, + Err(err) => { + println!("{err}"); + } + } + }); + + div_element.add_event_listener("click", real_click_handler, &event_listener_options, &exception_state).unwrap(); + + let text_node = document.create_text_node("From Rust", &exception_state).unwrap(); + + div_element.append_child(&text_node.as_node(), &exception_state).expect("append Node Failed"); + + document.body().append_child(&div_element.as_node(), &exception_state).unwrap(); + + let event_cleaner_element = document.create_element("button", &exception_state).unwrap(); + + let event_cleaner_text_node = document.create_text_node("Remove Event", &exception_state).unwrap(); + + event_cleaner_element.append_child(&event_cleaner_text_node.as_node(), &exception_state).unwrap(); + + let event_cleaner_handler = Box::new(move |event: &Event| { + let context = event.context(); + let exception_state = context.create_exception_state(); + + let _ = div_element.remove_event_listener("custom_click", event_handler.clone(), &exception_state); + }); + + event_cleaner_element.add_event_listener("click", event_cleaner_handler, &event_listener_options, &exception_state).unwrap(); + + document.body().append_child(&event_cleaner_element.as_node(), &exception_state).unwrap(); + + std::ptr::null_mut() +} diff --git a/webf/example/rust_builder/windows/.gitignore b/webf/example/rust_builder/windows/.gitignore new file mode 100644 index 0000000000..b3eb2be169 --- /dev/null +++ b/webf/example/rust_builder/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/webf/example/rust_builder/windows/CMakeLists.txt b/webf/example/rust_builder/windows/CMakeLists.txt new file mode 100644 index 0000000000..cf41998625 --- /dev/null +++ b/webf/example/rust_builder/windows/CMakeLists.txt @@ -0,0 +1,26 @@ +# The Flutter tooling requires that developers have CMake 3.10 or later +# installed. You should not increase this version, as doing so will cause +# the plugin to fail to compile for some customers of the plugin. +cmake_minimum_required(VERSION 3.10) + +# Project-level configuration. +set(PROJECT_NAME "example_app") +project(${PROJECT_NAME} LANGUAGES CXX) + + +# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> +# Replace add_subdirectory that references old C++ code with Cargokit: +include("../cargokit/cmake/cargokit.cmake") +apply_cargokit(${PROJECT_NAME} "../rust" example_app "") + +# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(example_app_bundled_libraries + "${${PROJECT_NAME}_cargokit_lib}" + # Defined in ../src/CMakeLists.txt. + # This can be changed to accommodate different builds. + PARENT_SCOPE +) \ No newline at end of file diff --git a/webf/example/windows/CMakeLists.txt b/webf/example/windows/CMakeLists.txt index c0270746b1..5415277110 100644 --- a/webf/example/windows/CMakeLists.txt +++ b/webf/example/windows/CMakeLists.txt @@ -8,7 +8,7 @@ set(BINARY_NAME "example") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. -cmake_policy(SET CMP0063 NEW) +cmake_policy(VERSION 3.14...3.25) # Define build configuration option. get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) @@ -52,6 +52,9 @@ add_subdirectory(${FLUTTER_MANAGED_DIR}) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") +# Enable the test target. +set(include_example_tests TRUE) + # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) @@ -86,6 +89,12 @@ if(PLUGIN_BUNDLED_LIBRARIES) COMPONENT Runtime) endif() +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") diff --git a/webf/example/windows/flutter/generated_plugins.cmake b/webf/example/windows/flutter/generated_plugins.cmake index e3552774d1..2384d51819 100644 --- a/webf/example/windows/flutter/generated_plugins.cmake +++ b/webf/example/windows/flutter/generated_plugins.cmake @@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + example_app ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/webf/example/windows/runner/CMakeLists.txt b/webf/example/windows/runner/CMakeLists.txt index 17411a8ab8..394917c053 100644 --- a/webf/example/windows/runner/CMakeLists.txt +++ b/webf/example/windows/runner/CMakeLists.txt @@ -33,6 +33,7 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. diff --git a/webf/example/windows/runner/flutter_window.cpp b/webf/example/windows/runner/flutter_window.cpp index b43b9095ea..955ee3038f 100644 --- a/webf/example/windows/runner/flutter_window.cpp +++ b/webf/example/windows/runner/flutter_window.cpp @@ -26,6 +26,16 @@ bool FlutterWindow::OnCreate() { } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + return true; } diff --git a/webf/example/windows/runner/main.cpp b/webf/example/windows/runner/main.cpp index 64dac8d1ed..7363e1d88f 100644 --- a/webf/example/windows/runner/main.cpp +++ b/webf/example/windows/runner/main.cpp @@ -26,8 +26,8 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, FlutterWindow window(project); Win32Window::Point origin(10, 10); - Win32Window::Size size(360, 720); - if (!window.CreateAndShow(L"example", origin, size)) { + Win32Window::Size size(1280, 720); + if (!window.Create(L"webf_example", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); diff --git a/webf/example/windows/runner/runner.exe.manifest b/webf/example/windows/runner/runner.exe.manifest index c977c4a425..153653e8d6 100644 --- a/webf/example/windows/runner/runner.exe.manifest +++ b/webf/example/windows/runner/runner.exe.manifest @@ -7,14 +7,8 @@ - + - - - - - - diff --git a/webf/example/windows/runner/utils.cpp b/webf/example/windows/runner/utils.cpp index f5bf9fa0f5..3a0b46511a 100644 --- a/webf/example/windows/runner/utils.cpp +++ b/webf/example/windows/runner/utils.cpp @@ -45,9 +45,11 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } - int target_length = ::WideCharToMultiByte( + unsigned int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr); + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); std::string utf8_string; if (target_length == 0 || target_length > utf8_string.max_size()) { return utf8_string; @@ -55,8 +57,7 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) { utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, utf8_string.data(), - target_length, nullptr, nullptr); + input_length, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } diff --git a/webf/example/windows/runner/win32_window.cpp b/webf/example/windows/runner/win32_window.cpp index c10f08dc7d..60608d0fe5 100644 --- a/webf/example/windows/runner/win32_window.cpp +++ b/webf/example/windows/runner/win32_window.cpp @@ -1,13 +1,31 @@ #include "win32_window.h" +#include #include #include "resource.h" namespace { +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; @@ -31,8 +49,8 @@ void EnableFullDpiSupportIfAvailable(HWND hwnd) { GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); - FreeLibrary(user32_module); } + FreeLibrary(user32_module); } } // namespace @@ -42,7 +60,7 @@ class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; - // Returns the singleton registar instance. + // Returns the singleton registrar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); @@ -102,9 +120,9 @@ Win32Window::~Win32Window() { Destroy(); } -bool Win32Window::CreateAndShow(const std::wstring& title, - const Point& origin, - const Size& size) { +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { Destroy(); const wchar_t* window_class = @@ -117,7 +135,7 @@ bool Win32Window::CreateAndShow(const std::wstring& title, double scale_factor = dpi / 96.0; HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); @@ -126,9 +144,15 @@ bool Win32Window::CreateAndShow(const std::wstring& title, return false; } + UpdateTheme(window); + return OnCreate(); } +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, @@ -188,6 +212,10 @@ Win32Window::MessageHandler(HWND hwnd, SetFocus(child_content_); } return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); @@ -243,3 +271,18 @@ bool Win32Window::OnCreate() { void Win32Window::OnDestroy() { // No-op; provided for subclasses. } + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/webf/example/windows/runner/win32_window.h b/webf/example/windows/runner/win32_window.h index 17ba431125..e901dde684 100644 --- a/webf/example/windows/runner/win32_window.h +++ b/webf/example/windows/runner/win32_window.h @@ -28,15 +28,16 @@ class Win32Window { Win32Window(); virtual ~Win32Window(); - // Creates and shows a win32 window with |title| and position and size using + // Creates a win32 window with |title| that is positioned and sized using // |origin| and |size|. New windows are created on the default monitor. Window // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size to will treat the width height passed in to this function - // as logical pixels and scale to appropriate for the default monitor. Returns - // true if the window was created successfully. - bool CreateAndShow(const std::wstring& title, - const Point& origin, - const Size& size); + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); // Release OS resources associated with window. void Destroy(); @@ -76,7 +77,7 @@ class Win32Window { // OS callback called by message pump. Handles the WM_NCCREATE message which // is passed when the non-client area is being created and enables automatic // non-client DPI scaling so that the non-client area automatically - // responsponds to changes in DPI. All other messages are handled by + // responds to changes in DPI. All other messages are handled by // MessageHandler. static LRESULT CALLBACK WndProc(HWND const window, UINT const message, @@ -86,6 +87,9 @@ class Win32Window { // Retrieves a class instance pointer for |window| static Win32Window* GetThisFromHandle(HWND const window) noexcept; + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + bool quit_on_close_ = false; // window handle for top level window. diff --git a/webf/lib/src/bridge/from_native.dart b/webf/lib/src/bridge/from_native.dart index a6ca2d9c64..d560dc30f8 100644 --- a/webf/lib/src/bridge/from_native.dart +++ b/webf/lib/src/bridge/from_native.dart @@ -5,9 +5,11 @@ import 'dart:async'; import 'dart:ffi'; +import 'dart:io'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; +import 'package:path/path.dart'; import 'package:webf/bridge.dart'; import 'package:webf/foundation.dart'; import 'package:webf/launcher.dart'; @@ -138,7 +140,8 @@ void _handleInvokeModuleResult(Object handle, Pointer result) { } dynamic invokeModule(Pointer callbackContext, WebFController controller, String moduleName, String method, params, - DartAsyncModuleCallback callback, { BindingOpItem? profileOp }) { + DartAsyncModuleCallback callback, + {BindingOpItem? profileOp}) { WebFViewController currentView = controller.view; dynamic result; @@ -184,7 +187,6 @@ dynamic invokeModule(Pointer callbackContext, WebFController controller, S if (enableWebFProfileTracking) { WebFProfiler.instance.finishTrackBindingSteps(profileOp!); } - } catch (e, stack) { if (enableWebFCommandLog) { print('Invoke module failed: $e\n$stack'); @@ -209,7 +211,6 @@ Pointer _invokeModule( Pointer method, Pointer params, Pointer> callback) { - BindingOpItem? currentProfileOp; if (enableWebFProfileTracking) { currentProfileOp = WebFProfiler.instance.startTrackBinding(profileLinkId); @@ -230,8 +231,9 @@ Pointer _invokeModule( WebFProfiler.instance.startTrackBindingSteps(currentProfileOp, 'invokeModule'); } - dynamic result = invokeModule(callbackContext, controller, moduleValue, methodValue, - paramsValue, callback.asFunction(), profileOp: currentProfileOp); + dynamic result = invokeModule( + callbackContext, controller, moduleValue, methodValue, paramsValue, callback.asFunction(), + profileOp: currentProfileOp); if (enableWebFProfileTracking) { WebFProfiler.instance.finishTrackBindingSteps(currentProfileOp!); @@ -447,9 +449,59 @@ void _createBindingObject( final Pointer> _nativeCreateBindingObject = Pointer.fromFunction(_createBindingObject); -typedef NativeGetWidgetElementShape = Int8 Function(Double contextId, Pointer nativeBindingObject, Pointer result); +typedef NativeLoadNativeLibrary = Void Function( + Double contextId, + Pointer libName, + Pointer initializeData, + Pointer importData, + Pointer> callback); +typedef NativeLoadNativeLibraryCallback = Pointer Function( + Pointer> entryPoint, + Pointer initializeData, Double contextId, Pointer exportData); +typedef DartLoadNativeLibraryCallback = Pointer Function( + Pointer> entryPoint, + Pointer initializeData, double contextId, Pointer exportData); + +typedef StandardWebFPluginExternalSymbol = Void Function(); +typedef DartStandardWebFPluginExternalSymbol = void Function(); + +String _getNativeLibraryName(String prefix) { + if (Platform.isMacOS || Platform.isIOS) { + return '$prefix.framework/$prefix'; + } else if (Platform.isWindows) { + return '$prefix.dll'; + } else if (Platform.isAndroid || Platform.isLinux) { + return 'lib$prefix.so'; + } else { + throw UnimplementedError('Not supported platform.'); + } +} + +void _loadNativeLibrary(double contextId, Pointer nativeLibName, Pointer initializeData, + Pointer importData, Pointer> nativeCallback) { + String libName = nativeStringToString(nativeLibName); + final String _defaultLibraryPath = Platform.isLinux ? '\$ORIGIN' : ''; + DartLoadNativeLibraryCallback callback = nativeCallback.asFunction(isLeaf: true); + try { + final library = DynamicLibrary.open(join(_defaultLibraryPath, _getNativeLibraryName(libName))); + String entrySymbol = Platform.environment['WEBF_ENABLE_TEST'] != null ? 'init_webf_test_app' : 'init_webf_app'; + Pointer> nativeFunction = + library.lookup>(entrySymbol); + + callback(nativeFunction, initializeData, contextId, importData); + } catch (e, stack) { + String errmsg = '$e\n$stack'; + callback(nullptr, initializeData, contextId, errmsg.toNativeUtf8().cast()); + } +} + +final Pointer> _nativeLoadLibrary = Pointer.fromFunction(_loadNativeLibrary); + +typedef NativeGetWidgetElementShape = Int8 Function( + Double contextId, Pointer nativeBindingObject, Pointer result); -int _getWidgetElementShape(double contextId, Pointer nativeBindingObject, Pointer result) { +int _getWidgetElementShape( + double contextId, Pointer nativeBindingObject, Pointer result) { try { WebFController controller = WebFController.getControllerOfJSContextId(contextId)!; DynamicBindingObject object = controller.view.getBindingObject(nativeBindingObject)!; @@ -464,7 +516,8 @@ int _getWidgetElementShape(double contextId, Pointer native return 0; } -final Pointer> _nativeGetWidgetElementShape = Pointer.fromFunction(_getWidgetElementShape, 0); +final Pointer> _nativeGetWidgetElementShape = + Pointer.fromFunction(_getWidgetElementShape, 0); typedef NativeJSError = Void Function(Double contextId, Pointer); @@ -508,6 +561,7 @@ final List _dartNativeMethods = [ _nativeToBlob.address, _nativeFlushUICommand.address, _nativeCreateBindingObject.address, + _nativeLoadLibrary.address, _nativeGetWidgetElementShape.address, _nativeOnJsError.address, _nativeOnJsLog.address, diff --git a/webf/lib/src/css/values/length.dart b/webf/lib/src/css/values/length.dart index a93d272ba6..62b9e67a3b 100644 --- a/webf/lib/src/css/values/length.dart +++ b/webf/lib/src/css/values/length.dart @@ -66,7 +66,7 @@ class CSSLengthValue { } if (isViewportSizeRelatedLength()) { - renderStyle!.addViewportSizeRelativeProperty(); + renderStyle?.addViewportSizeRelativeProperty(); } } diff --git a/webf/linux/CMakeLists.txt b/webf/linux/CMakeLists.txt index dfadaf7f56..294a066273 100644 --- a/webf/linux/CMakeLists.txt +++ b/webf/linux/CMakeLists.txt @@ -8,37 +8,36 @@ set(PLUGIN_NAME "webf_plugin") add_library(${PLUGIN_NAME} SHARED "webf_plugin.cc" - ) - -add_library(webf SHARED IMPORTED) -set_target_properties(webf PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/libwebf.so") -add_library(quickjs SHARED IMPORTED) -set_target_properties(quickjs PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/libquickjs.so") +) +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. set_target_properties(${PLUGIN_NAME} PROPERTIES - CXX_VISIBILITY_PRESET hidden) + CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. target_include_directories(${PLUGIN_NAME} INTERFACE - "${CMAKE_CURRENT_SOURCE_DIR}/include") + "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) -execute_process( - COMMAND bash "-c" "readlink -f ${CMAKE_CURRENT_SOURCE_DIR}/libwebf.so" - OUTPUT_VARIABLE WEBF_LIB_PATH -) -string(REGEX REPLACE "\n$" "" WEBF_LIB_PATH "${WEBF_LIB_PATH}") -execute_process( - COMMAND bash "-c" "readlink -f ${CMAKE_CURRENT_SOURCE_DIR}/libquickjs.so" - OUTPUT_VARIABLE QUICKJS_LIB_PATH -) -string(REGEX REPLACE "\n$" "" QUICKJS_LIB_PATH "${QUICKJS_LIB_PATH}") +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") + # List of absolute paths to libraries that should be bundled with the plugin set(webf_bundled_libraries - ${QUICKJS_LIB_PATH} - ${WEBF_LIB_PATH} + $ + $ PARENT_SCOPE ) diff --git a/webf/linux/libquickjs.so b/webf/linux/libquickjs.so deleted file mode 120000 index 04336e15f6..0000000000 --- a/webf/linux/libquickjs.so +++ /dev/null @@ -1 +0,0 @@ -../../bridge/build/linux/lib/libquickjs.so \ No newline at end of file diff --git a/webf/linux/libwebf.so b/webf/linux/libwebf.so deleted file mode 120000 index f7c0994ea9..0000000000 --- a/webf/linux/libwebf.so +++ /dev/null @@ -1 +0,0 @@ -../../bridge/build/linux/lib/libwebf.so \ No newline at end of file diff --git a/webf/src b/webf/src new file mode 120000 index 0000000000..f7bd1c9463 --- /dev/null +++ b/webf/src @@ -0,0 +1 @@ +../bridge \ No newline at end of file diff --git a/webf/win_src b/webf/win_src new file mode 120000 index 0000000000..f7bd1c9463 --- /dev/null +++ b/webf/win_src @@ -0,0 +1 @@ +../bridge \ No newline at end of file diff --git a/webf/windows/CMakeLists.txt b/webf/windows/CMakeLists.txt index f78e07da8b..f820af665c 100644 --- a/webf/windows/CMakeLists.txt +++ b/webf/windows/CMakeLists.txt @@ -7,27 +7,35 @@ project(${PROJECT_NAME} LANGUAGES CXX) set(PLUGIN_NAME "webf_plugin") add_library(${PLUGIN_NAME} SHARED - "webf_plugin.cpp" + "webf_plugin.cpp" ) +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) - target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) -execute_process( - COMMAND powershell "-c" "node prepare.js" - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} -) +# Invoke the build for native code shared with the other target platforms. +# This can be changed to accommodate different builds. +add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../win_src" "${CMAKE_CURRENT_BINARY_DIR}/shared") # List of absolute paths to libraries that should be bundled with the plugin set(webf_bundled_libraries - ${CMAKE_CURRENT_SOURCE_DIR}/pthreadVC2.dll - ${CMAKE_CURRENT_SOURCE_DIR}/quickjs.dll - ${CMAKE_CURRENT_SOURCE_DIR}/webf.dll - PARENT_SCOPE -) + $ + $ + $ + PARENT_SCOPE + ) diff --git a/webf/windows/prepare.js b/webf/windows/prepare.js deleted file mode 100644 index 32808489d7..0000000000 --- a/webf/windows/prepare.js +++ /dev/null @@ -1,17 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -function replaceTextToDLL(p) { - const fileExt = p.slice(-3); - p = path.isAbsolute(p) ? p : path.join(__dirname, p); - const dist = p.replace('.txt', '.dll').trim(); - if (fileExt === 'txt' && fs.existsSync(p)) { - const relPath = fs.readFileSync(p, {encoding: 'utf-8'}); - const targetPath = path.join(__dirname, relPath); - fs.createReadStream(targetPath.trim()).pipe(fs.createWriteStream(p.replace('.txt', '.dll').trim())) - } -} -// -replaceTextToDLL('./webf.txt'); -replaceTextToDLL('./pthreadVC2.txt'); -replaceTextToDLL('./quickjs.txt'); diff --git a/webf/windows/pthreadVC2.txt b/webf/windows/pthreadVC2.txt deleted file mode 100644 index 7ffde5d85e..0000000000 --- a/webf/windows/pthreadVC2.txt +++ /dev/null @@ -1 +0,0 @@ -../../bridge/build/windows/lib/pthreadVC2.dll diff --git a/webf/windows/quickjs.txt b/webf/windows/quickjs.txt deleted file mode 100644 index df34679a3d..0000000000 --- a/webf/windows/quickjs.txt +++ /dev/null @@ -1 +0,0 @@ -../../bridge/build/windows/lib/quickjs.dll diff --git a/webf/windows/webf.txt b/webf/windows/webf.txt deleted file mode 100644 index d192dcea00..0000000000 --- a/webf/windows/webf.txt +++ /dev/null @@ -1 +0,0 @@ -../../bridge/build/windows/lib/webf.dll \ No newline at end of file