Skip to content

Commit b3e2d68

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 5758cea commit b3e2d68

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

compat/mingw.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ static int retry_ask_yes_no(int *tries, const char *format, ...)
228228
return result;
229229
}
230230

231+
232+
DECLARE_PROC_ADDR(kernel32.dll, BOOL, CreateSymbolicLinkW, LPCWSTR, LPCWSTR, DWORD);
233+
231234
/* Normalizes NT paths as returned by some low-level APIs. */
232235
static wchar_t *normalize_ntpath(wchar_t *wbuf)
233236
{
@@ -2084,6 +2087,34 @@ int link(const char *oldpath, const char *newpath)
20842087
return 0;
20852088
}
20862089

2090+
int symlink(const char *target, const char *link)
2091+
{
2092+
wchar_t wtarget[MAX_LONG_PATH], wlink[MAX_LONG_PATH];
2093+
int len;
2094+
2095+
/* fail if symlinks are disabled or API is not supported (WinXP) */
2096+
if (!has_symlinks || !INIT_PROC_ADDR(CreateSymbolicLinkW)) {
2097+
errno = ENOSYS;
2098+
return -1;
2099+
}
2100+
2101+
if ((len = xutftowcs_long_path(wtarget, target)) < 0
2102+
|| xutftowcs_long_path(wlink, link) < 0)
2103+
return -1;
2104+
2105+
/* convert target dir separators to backslashes */
2106+
while (len--)
2107+
if (wtarget[len] == '/')
2108+
wtarget[len] = '\\';
2109+
2110+
/* create file symlink */
2111+
if (!CreateSymbolicLinkW(wlink, wtarget, 0)) {
2112+
errno = err_win_to_posix(GetLastError());
2113+
return -1;
2114+
}
2115+
return 0;
2116+
}
2117+
20872118
#ifndef _WINNT_H
20882119
/*
20892120
* 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
@@ -117,8 +117,6 @@ struct utsname {
117117
* trivial stubs
118118
*/
119119

120-
static inline int symlink(const char *oldpath, const char *newpath)
121-
{ errno = ENOSYS; return -1; }
122120
static inline int fchmod(int fildes, mode_t mode)
123121
{ errno = ENOSYS; return -1; }
124122
#ifndef __MINGW64_VERSION_MAJOR
@@ -210,6 +208,7 @@ int setitimer(int type, struct itimerval *in, struct itimerval *out);
210208
int sigaction(int sig, struct sigaction *in, struct sigaction *out);
211209
int link(const char *oldpath, const char *newpath);
212210
int uname(struct utsname *buf);
211+
int symlink(const char *target, const char *link);
213212
int readlink(const char *path, char *buf, size_t bufsiz);
214213

215214
/*

0 commit comments

Comments
 (0)