Hold a plugin reference while TSRemapInit runs

A new remap plugin has no reference until its first instance takes
one. A thread that the plugin starts in TSRemapInit, and that returns
before that, released the last reference and unloaded the plugin.
The factory now holds a reference from the load until the first
instance exists.
diff --git a/doc/developer-guide/design-documents/reloading-plugins.en.rst b/doc/developer-guide/design-documents/reloading-plugins.en.rst
index 352ed16..a1b79bf 100644
--- a/doc/developer-guide/design-documents/reloading-plugins.en.rst
+++ b/doc/developer-guide/design-documents/reloading-plugins.en.rst
@@ -129,7 +129,7 @@
 
 A thread from ``TSThreadCreate`` gets the plugin context of the code that created it, and holds a reference
 to that context until the thread function returns. Thus continuations that the thread creates are also
-reference counted.
+reference counted. A plugin that is not in use stays loaded until its threads return.
 
 
 TSUserArgs
diff --git a/src/proxy/http/remap/PluginFactory.cc b/src/proxy/http/remap/PluginFactory.cc
index 6ae2cde..a73bda8 100644
--- a/src/proxy/http/remap/PluginFactory.cc
+++ b/src/proxy/http/remap/PluginFactory.cc
@@ -219,6 +219,10 @@
     if (nullptr != plugin) {
       bool loaded      = false;
       bool initialized = false;
+
+      // TSRemapInit can take and release a reference, for example with a thread that returns. This
+      // reference keeps the plugin until the first instance has its own reference.
+      plugin->acquire();
       {
         // TSRemapInit is plugin-global: hide the loading rule from the strategy APIs.
         UrlMappingInstanceScope const no_rule{nullptr};
@@ -235,6 +239,7 @@
             /* Plugin loading and instance init went fine. */
             _instList.append(inst);
           }
+          plugin->release();
         } else {
           /* Plugin DSO load succeeded but instance init failed. */
           PluginDbg(_dbg_ctl(), "plugin '%s' instance init failed", configPath.c_str());
diff --git a/src/proxy/http/remap/unit-tests/CMakeLists.txt b/src/proxy/http/remap/unit-tests/CMakeLists.txt
index 11c7c45..e457280 100644
--- a/src/proxy/http/remap/unit-tests/CMakeLists.txt
+++ b/src/proxy/http/remap/unit-tests/CMakeLists.txt
@@ -52,6 +52,8 @@
 #
 add_plugin_ut_lib(plugin_init_fail plugin_init_fail.cc plugin_stub.cc)
 #
+add_plugin_ut_lib(plugin_init_hook plugin_init_hook.cc plugin_stub.cc)
+#
 add_plugin_ut_lib(plugin_instinit_fail plugin_instinit_fail.cc plugin_stub.cc)
 #
 add_plugin_ut_lib(plugin_required_cb plugin_required_cb.cc plugin_stub.cc)
diff --git a/src/proxy/http/remap/unit-tests/plugin_init_hook.cc b/src/proxy/http/remap/unit-tests/plugin_init_hook.cc
new file mode 100644
index 0000000..5f8ba62
--- /dev/null
+++ b/src/proxy/http/remap/unit-tests/plugin_init_hook.cc
@@ -0,0 +1,57 @@
+/** @file
+
+  A test plugin for testing Plugin's Dynamic Shared Objects (DSO)
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you 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.
+
+  @section details Details
+
+  Implements code necessary for Reverse Proxy which mostly consists of
+  general purpose hostname substitution in URLs.
+
+ */
+
+#include "plugin_testing_common.h"
+
+#include "ts/ts.h"
+#include "ts/remap.h"
+
+#include <cstdlib>
+
+TSReturnCode
+TSRemapInit([[maybe_unused]] TSRemapInterface *api_info, [[maybe_unused]] char *errbuf, [[maybe_unused]] int errbuf_size)
+{
+  // The test gives the address of a function to call during TSRemapInit. The function runs in the
+  // test executable, because this DSO has its own copy of the thread-local plugin context.
+  if (const char *hook = getenv("TS_TEST_REMAP_INIT_HOOK"); hook != nullptr) {
+    reinterpret_cast<void (*)()>(strtoull(hook, nullptr, 10))();
+  }
+  return TS_SUCCESS;
+}
+
+void
+TSRemapDone(void)
+{
+}
+
+TSRemapStatus
+TSRemapDoRemap([[maybe_unused]] void *ih, [[maybe_unused]] TSHttpTxn rh, [[maybe_unused]] TSRemapRequestInfo *rri)
+{
+  return TSREMAP_NO_REMAP;
+}
diff --git a/src/proxy/http/remap/unit-tests/test_PluginFactory.cc b/src/proxy/http/remap/unit-tests/test_PluginFactory.cc
index e021cfd..29bbda1 100644
--- a/src/proxy/http/remap/unit-tests/test_PluginFactory.cc
+++ b/src/proxy/http/remap/unit-tests/test_PluginFactory.cc
@@ -438,6 +438,32 @@
       teardownConfigPathTest();
     }
 
+    WHEN("plugin initialization reads the reference count of the plugin")
+    {
+      fs::path configPath = fs::path("plugin_init_hook.so");
+      fs::path buildPath  = pluginBuildDir / configPath;
+      setupConfigPathTest(configPath, buildPath, tempComponent, effectivePath, runtimePath);
+
+      // Without a reference during TSRemapInit, a thread from TSThreadCreate that returns there
+      // releases the last reference and unloads the plugin.
+      static int references_in_init;
+      references_in_init = -1;
+      void (*hook)()     = [] { references_in_init = pluginThreadContext->refcount(); };
+      setenv("TS_TEST_REMAP_INIT_HOOK", std::to_string(reinterpret_cast<uintptr_t>(hook)).c_str(), 1);
+      auto             factory = getFactory(tempComponent);
+      RemapPluginInst *plugin  = factory->getRemapPlugin(configPath, 0, nullptr, error, isPluginDynamicReloadEnabled());
+      unsetenv("TS_TEST_REMAP_INIT_HOOK");
+
+      THEN("expect the factory to hold a reference during the initialization")
+      {
+        CHECK(references_in_init == 1);
+        CHECK(nullptr != plugin);
+        CHECK(nullptr != PluginDso::loadedPlugins()->findByEffectivePath(effectivePath, isPluginDynamicReloadEnabled()));
+      }
+
+      teardownConfigPathTest();
+    }
+
     WHEN("instance initialization fails")
     {
       fs::path configPath = fs::path("plugin_instinit_fail.so");