*** a/doc/src/sgml/extend.sgml
--- b/doc/src/sgml/extend.sgml
***************
*** 462,467 ****
--- 462,474 ----
          FUNCTION</> commands for C-language functions, so that the script
          files do not need to hard-wire the name of the shared library.
         </para>
+        <para>
+         The macro <literal>$directory</literal> is supported when found at the
+         very start of the value of this parameter. When
+         used, <literal>$directory</literal> is then substituted with
+         the <literal>directory</literal> control parameter value by
+         PostgreSQL.
+        </para>
        </listitem>
       </varlistentry>
  
*** a/src/backend/commands/extension.c
--- b/src/backend/commands/extension.c
***************
*** 432,437 **** get_extension_script_filename(ExtensionControlFile *control,
--- 432,470 ----
  	return result;
  }
  
+ /*
+  * Substitute for any macros appearing in the given string.
+  * Result is always freshly palloc'd.
+  */
+ static char *
+ substitute_directory_macro(const char *directory, const char *module_pathname)
+ {
+ 	const char *sep_ptr;
+ 
+ 	AssertArg(module_pathname != NULL);
+ 
+ 	/* Currently, we only recognize $directory at the start of the string */
+ 	if (module_pathname[0] != '$')
+ 		return pstrdup(module_pathname);
+ 
+ 	if ((sep_ptr = first_dir_separator(module_pathname)) == NULL)
+ 		sep_ptr = module_pathname + strlen(module_pathname);
+ 
+ 	/* Accept $libdir, just return module_pathname as is then */
+ 	if (strlen("$libdir") == sep_ptr - module_pathname &&
+ 		strncmp(module_pathname, "$libdir", strlen("$libdir")) == 0)
+ 		return pstrdup(module_pathname);
+ 
+ 	if (strlen("$directory") != sep_ptr - module_pathname ||
+ 		strncmp(module_pathname, "$directory", strlen("$directory")) != 0)
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_INVALID_NAME),
+ 				 errmsg("invalid macro module_pathname in: %s",
+ 						module_pathname)));
+ 
+ 	return psprintf("%s%s", directory, sep_ptr);
+ }
+ 
  
  /*
   * Parse contents of primary or auxiliary control file, and fill in
***************
*** 895,904 **** execute_extension_script(Oid extensionOid, ExtensionControlFile *control,
  		 */
  		if (control->module_pathname)
  		{
  			t_sql = DirectFunctionCall3(replace_text,
  										t_sql,
  									  CStringGetTextDatum("MODULE_PATHNAME"),
! 							  CStringGetTextDatum(control->module_pathname));
  		}
  
  		/* And now back to C string */
--- 928,941 ----
  		 */
  		if (control->module_pathname)
  		{
+ 			char *directory = get_extension_script_directory(control);
+ 			char *module_pathname =
+ 				substitute_directory_macro(directory, control->module_pathname);
+ 
  			t_sql = DirectFunctionCall3(replace_text,
  										t_sql,
  									  CStringGetTextDatum("MODULE_PATHNAME"),
! 							  CStringGetTextDatum(module_pathname));
  		}
  
  		/* And now back to C string */
