Skip to content

Commit d10e02f

Browse files
kbleesdscho
authored andcommitted
Win32: implement basic symlink() functionality (file symlinks only)
Implement symlink() that always creates file symlinks. Fails with ENOSYS if symlinks are disabled or unsupported. Note: CreateSymbolicLinkW() was introduced with symlink support in Windows Vista. For compatibility with Windows XP, we need to load it dynamically and fail gracefully if it isnt's available. Signed-off-by: Karsten Blees <[email protected]>
1 parent b8c6d3f commit d10e02f

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

compat/mingw.c

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,8 @@ int mingw_core_config(const char *var, const char *value, void *cb)
270270
return 0;
271271
}
272272

273+
DECLARE_PROC_ADDR(kernel32.dll, BOOLEAN, CreateSymbolicLinkW, LPCWSTR, LPCWSTR, DWORD);
274+
273275
/* Normalizes NT paths as returned by some low-level APIs. */
274276
static wchar_t *normalize_ntpath(wchar_t *wbuf)
275277
{
@@ -2172,6 +2174,34 @@ int link(const char *oldpath, const char *newpath)
21722174
return 0;
21732175
}
21742176

2177+
int symlink(const char *target, const char *link)
2178+
{
2179+
wchar_t wtarget[MAX_LONG_PATH], wlink[MAX_LONG_PATH];
2180+
int len;
2181+
2182+
/* fail if symlinks are disabled or API is not supported (WinXP) */
2183+
if (!has_symlinks || !INIT_PROC_ADDR(CreateSymbolicLinkW)) {
2184+
errno = ENOSYS;
2185+
return -1;
2186+
}
2187+
2188+
if ((len = xutftowcs_long_path(wtarget, target)) < 0
2189+
|| xutftowcs_long_path(wlink, link) < 0)
2190+
return -1;
2191+
2192+
/* convert target dir separators to backslashes */
2193+
while (len--)
2194+
if (wtarget[len] == '/')
2195+
wtarget[len] = '\\';
2196+
2197+
/* create file symlink */
2198+
if (!CreateSymbolicLinkW(wlink, wtarget, 0)) {
2199+
errno = err_win_to_posix(GetLastError());
2200+
return -1;
2201+
}
2202+
return 0;
2203+
}
2204+
21752205
#ifndef _WINNT_H
21762206
/*
21772207
* The REPARSE_DATA_BUFFER structure is defined in the Windows DDK (in

compat/mingw.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,6 @@ struct utsname {
123123
* trivial stubs
124124
*/
125125

126-
static inline int symlink(const char *oldpath, const char *newpath)
127-
{ errno = ENOSYS; return -1; }
128126
static inline int fchmod(int fildes, mode_t mode)
129127
{ errno = ENOSYS; return -1; }
130128
#ifndef __MINGW64_VERSION_MAJOR
@@ -223,6 +221,7 @@ int setitimer(int type, struct itimerval *in, struct itimerval *out);
223221
int sigaction(int sig, struct sigaction *in, struct sigaction *out);
224222
int link(const char *oldpath, const char *newpath);
225223
int uname(struct utsname *buf);
224+
int symlink(const char *target, const char *link);
226225
int readlink(const char *path, char *buf, size_t bufsiz);
227226

228227
/*

0 commit comments

Comments
 (0)