Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CreateDirectory: eliminate some syscalls. #58799

Merged
merged 4 commits into from
Nov 18, 2021
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 94 additions & 68 deletions src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -272,101 +272,127 @@ public static void DeleteFile(string fullPath)

public static void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
// The argument is a full path, which means it is an absolute path that
// doesn't contain "//", "/./", and "/../".
Debug.Assert(fullPath.Length > 0);
Debug.Assert(PathInternal.IsDirectorySeparator(fullPath[0]));

int length = fullPath.Length;

// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && Path.EndsInDirectorySeparator(fullPath))
if (fullPath.Length == 1)
{
length--;
// fullPath is '/'.
return;
}

// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
string mkdirPath = fullPath;
int result = Interop.Sys.MkDir(mkdirPath, (int)Interop.Sys.Permissions.Mask);
if (result == 0)
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
// Created directory.
return;
}

// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
{
return;
// Path already exists. Ensure it's a directory.
if (DirectoryExists(fullPath))
{
return;
}
}

// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
List<string> stackDir = new List<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
else if (errorInfo.Error == Interop.Error.ENOENT)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
// Some parts of the path don't exist yet.

// Try create parents bottom to top and track those that could not
// be created due to missing parents. Then create them top to bottom.

List<string> stackDir = new List<string>();

stackDir.Add(fullPath);

int i = fullPath.Length - 1;
// Trim trailing separator.
if (PathInternal.IsDirectorySeparator(fullPath[i]))
{
if (!DirectoryExists(fullPath.AsSpan(0, i + 1))) // Create only the ones missing
i--;
}
do
{
// Find the end of the parent directory.
Debug.Assert(!PathInternal.IsDirectorySeparator(fullPath[i]));
while (!PathInternal.IsDirectorySeparator(fullPath[i]))
{
stackDir.Add(fullPath.Substring(0, i + 1));
i--;
}
else

// Try create it.
mkdirPath = fullPath.Substring(0, i);
result = Interop.Sys.MkDir(mkdirPath, (int)Interop.Sys.Permissions.Mask);
if (result == 0)
{
somepathexists = true;
// Created parent.
break;
}

while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.ENOENT)
{
i--;
// Some parts of the path don't exist yet.
// We'll try to create its parent on the next iteration.

// Track this path for later creation.
stackDir.Add(mkdirPath);
}
else if (errorInfo.Error == Interop.Error.EEXIST)
{
// Parent exists.
// If it is not a directory, MkDir will fail when we create a child directory.
result = 0;
break;
}
else
{
// Fail.
break;
}
i--;
}
}

int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
ReadOnlySpan<char> root = Path.GetPathRoot(fullPath.AsSpan());
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
} while (i > 0);

// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
for (int i = stackDir.Count - 1; i >= 0; i--)
{
string name = stackDir[i];

// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
if (result < 0 && firstError.Error == 0)
if (result == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();

// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
// Create directories that had missing parents.
for (i = stackDir.Count - 1; i >= 0; i--)
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
mkdirPath = stackDir[i];
result = Interop.Sys.MkDir(mkdirPath, (int)Interop.Sys.Permissions.Mask);
if (result < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();

if (errorInfo.Error == Interop.Error.EEXIST)
{
// Path was created since we last checked.
// Continue, and for the last item, which is fullPath,
// verify it is actually a directory.
if (i == 0 && DirectoryExists(mkdirPath))
{
return;
}
}
else
{
// Fail.
break;
}
}
}
}
}

// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
if (result < 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
throw Interop.GetExceptionForIoErrno(errorInfo, mkdirPath, isDirectory: true);
}
}

Expand Down