Exemplo n.º 1
0
static BOOL do_searchW(PCWSTR file, PWSTR buffer, BOOL recurse,
                       PENUMDIRTREE_CALLBACKW cb, PVOID user)
{
    HANDLE              h;
    WIN32_FIND_DATAW    fd;
    unsigned            pos;
    BOOL                found = FALSE;
    static const WCHAR  S_AllW[] = {'*','.','*','\0'};
    static const WCHAR  S_DotW[] = {'.','\0'};
    static const WCHAR  S_DotDotW[] = {'.','.','\0'};

    pos = strlenW(buffer);
    if (buffer[pos - 1] != '\\') buffer[pos++] = '\\';
    strcpyW(buffer + pos, S_AllW);
    if ((h = FindFirstFileW(buffer, &fd)) == INVALID_HANDLE_VALUE)
        return FALSE;
    /* doc doesn't specify how the tree is enumerated...
     * doing a depth first based on, but may be wrong
     */
    do
    {
        if (!strcmpW(fd.cFileName, S_DotW) || !strcmpW(fd.cFileName, S_DotDotW)) continue;

        strcpyW(buffer + pos, fd.cFileName);
        if (recurse && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
            found = do_searchW(file, buffer, TRUE, cb, user);
        else if (SymMatchFileNameW(buffer, (WCHAR*)file, NULL, NULL))
        {
            if (!cb || cb(buffer, user)) found = TRUE;
        }
    } while (!found && FindNextFileW(h, &fd));
    if (!found) buffer[--pos] = '\0';
    FindClose(h);

    return found;
}
Exemplo n.º 2
0
///////////////////////////////////////////////////////////////
//
// FindFiles
//
// Find all files or directories at a path
// If sorted by date, returns last modified last
//
///////////////////////////////////////////////////////////////
std::vector<SString> SharedUtil::FindFiles(const SString& strInMatch, bool bFiles, bool bDirectories, bool bSortByDate)
{
    std::vector<SString>           strResult;
    std::multimap<uint64, SString> sortMap;

    SString strMatch = PathConform(strInMatch);
    if (strMatch.Right(1) == PATH_SEPERATOR)
        strMatch += "*";

    WIN32_FIND_DATAW findData;
    HANDLE           hFind = FindFirstFileW(FromUTF8(strMatch), &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? bDirectories : bFiles)
                if (wcscmp(findData.cFileName, L".") && wcscmp(findData.cFileName, L".."))
                {
                    if (bSortByDate)
                        MapInsert(sortMap, (uint64&)findData.ftLastWriteTime, ToUTF8(findData.cFileName));
                    else
                        strResult.push_back(ToUTF8(findData.cFileName));
                }
        } while (FindNextFileW(hFind, &findData));
        FindClose(hFind);
    }

    // Resolve sorted map if required
    if (!sortMap.empty())
    {
        for (std::multimap<uint64, SString>::iterator iter = sortMap.begin(); iter != sortMap.end(); ++iter)
            strResult.push_back(iter->second);
    }

    return strResult;
}
Exemplo n.º 3
0
std::wstring find_path_for_lates_log_file(const std::wstring& path_) {
    auto search = path_ + L"\\combat_*.txt";

    WIN32_FIND_DATAW info{};
    auto handle = FindFirstFileW(search.c_str(), &info);

    if ( handle != INVALID_HANDLE_VALUE ) {
        BOOST_SCOPE_EXIT_ALL(= ) {
            FindClose(handle);
        };

        auto last_info = info;

        do {
            BOOST_LOG_TRIVIAL(debug) << L"log file found " << info.cFileName;
            if ( CompareFileTime(&last_info.ftCreationTime, &info.ftCreationTime) < 0 ) {
                last_info = info;
            }
        } while ( FindNextFileW(handle, &info) );

        BOOST_LOG_TRIVIAL(debug) << L"newest log file is " << last_info.cFileName;

        return path_ + L"\\" + last_info.cFileName;
    }
Exemplo n.º 4
0
bool FileEnum::next_nt(bool& more) {
  while (true) {
    if (h_find == INVALID_HANDLE_VALUE) {
      h_find = FindFirstFileW(long_path(file_mask).c_str(), &find_data);
      if (h_find == INVALID_HANDLE_VALUE)
        return false;
    }
    else {
      if (!FindNextFileW(h_find, &find_data)) {
        if (GetLastError() == ERROR_NO_MORE_FILES) {
          more = false;
          return true;
        }
        return false;
      }
    }
    if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
      if ((find_data.cFileName[0] == L'.') && ((find_data.cFileName[1] == 0) || ((find_data.cFileName[1] == L'.') && (find_data.cFileName[2] == 0))))
        continue;
    }
    more = true;
    return true;
  }
}
void FFileManagerWindows::InternalFindFiles( TArray<FString>& Result, const TCHAR* Filename, UBOOL Files, UBOOL Directories )
{
	HANDLE Handle=NULL;
	WIN32_FIND_DATAW Data;
	Handle=FindFirstFileW(Filename,&Data);
	if( Handle!=INVALID_HANDLE_VALUE )
	{
		do
		{
			if
			(   appStricmp(Data.cFileName,TEXT("."))
			&&  appStricmp(Data.cFileName,TEXT(".."))
			&&  ((Data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)?Directories:Files) )
			{
				new(Result)FString(Data.cFileName);
			}
		}
		while( FindNextFileW(Handle,&Data) );
	}
	if( Handle!=INVALID_HANDLE_VALUE )
	{
		FindClose( Handle );
	}
}
Exemplo n.º 6
0
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_WindowsFileFunctions_readdir(JNIEnv *env, jclass target, jstring path, jobject contents, jobject result) {
    jclass contentsClass = env->GetObjectClass(contents);
    jmethodID mid = env->GetMethodID(contentsClass, "addFile", "(Ljava/lang/String;IJJ)V");
    if (mid == NULL) {
        mark_failed_with_message(env, "could not find method", result);
        return;
    }

    WIN32_FIND_DATAW entry;
    wchar_t* pathStr = java_to_wchar(env, path, result);
    HANDLE dirHandle = FindFirstFileW(pathStr, &entry);
    free(pathStr);
    if (dirHandle == INVALID_HANDLE_VALUE) {
        mark_failed_with_errno(env, "could not open directory", result);
        return;
    }

    do {
        if (wcscmp(L".", entry.cFileName) == 0 || wcscmp(L"..", entry.cFileName) == 0) {
            continue;
        }
        jstring childName = wchar_to_java(env, entry.cFileName, wcslen(entry.cFileName), result);
        jint type = (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? FILE_TYPE_DIRECTORY : FILE_TYPE_FILE;
        jlong lastModified = lastModifiedNanos(&entry.ftLastWriteTime);
        jlong size = ((jlong)entry.nFileSizeHigh << 32) | entry.nFileSizeLow;
        env->CallVoidMethod(contents, mid, childName, type, size, lastModified);
    } while (FindNextFileW(dirHandle, &entry) != 0);

    DWORD error = GetLastError();
    if (error != ERROR_NO_MORE_FILES ) {
        mark_failed_with_errno(env, "could not read next directory entry", result);
    }

    FindClose(dirHandle);
}
Exemplo n.º 7
0
static SHIMGVW_FILENODE*
pBuildFileList(LPWSTR szFirstFile)
{
    HANDLE hFindHandle;
    WCHAR *extension;
    WCHAR szSearchPath[MAX_PATH];
    WCHAR szSearchMask[MAX_PATH];
    WCHAR szFileTypes[MAX_PATH];
    WIN32_FIND_DATAW findData;
    SHIMGVW_FILENODE *currentNode;
    SHIMGVW_FILENODE *root;
    SHIMGVW_FILENODE *conductor;
    ImageCodecInfo *codecInfo;
    UINT num;
    UINT size;
    UINT j;


    wcscpy(szSearchPath, szFirstFile);
    PathRemoveFileSpecW(szSearchPath);

    GdipGetImageDecodersSize(&num, &size);
    codecInfo = malloc(size);
    if (!codecInfo)
    {
        DPRINT1("malloc() failed in pLoadFileList()\n");
        return NULL;
    }

    GdipGetImageDecoders(num, size, codecInfo);

    root = malloc(sizeof(SHIMGVW_FILENODE));
    if (!root)
    {
        DPRINT1("malloc() failed in pLoadFileList()\n");
        free(codecInfo);
        return NULL;
    }

    conductor = root;

    for (j = 0; j < num; ++j)
    {
        StringCbPrintfExW(szFileTypes, MAX_PATH, NULL, NULL, 0, L"%ls", codecInfo[j].FilenameExtension);
        
        extension = wcstok(szFileTypes, L";");
        while (extension != NULL)
        {
            StringCbPrintfExW(szSearchMask, MAX_PATH, NULL, NULL, 0, L"%ls%ls%ls", szSearchPath, L"\\", extension);

            hFindHandle = FindFirstFileW(szSearchMask, &findData);
            if (hFindHandle != INVALID_HANDLE_VALUE)
            {
                do
                {
                    StringCbPrintfExW(conductor->FileName, MAX_PATH, NULL, NULL, 0, L"%ls%ls%ls", szSearchPath, L"\\", findData.cFileName);

                    // compare the name of the requested file with the one currently found.
                    // if the name matches, the current node is returned by the function.
                    if (wcscmp(szFirstFile, conductor->FileName) == 0)
                    {
                        currentNode = conductor;
                    }

                    conductor->Next = malloc(sizeof(SHIMGVW_FILENODE));

                    // if malloc fails, make circular what we have and return it
                    if (!conductor->Next)
                    {
                        DPRINT1("malloc() failed in pLoadFileList()\n");
                        
                        conductor->Next = root;
                        root->Prev = conductor;

                        FindClose(hFindHandle);
                        free(codecInfo);
                        return conductor;
                    }

                    conductor->Next->Prev = conductor;
                    conductor = conductor->Next;
                }
                while (FindNextFileW(hFindHandle, &findData) != 0);

                FindClose(hFindHandle);
            }

            extension = wcstok(NULL, L";");
        }
    }

    // we now have a node too much in the list. In case the requested file was not found,
    // we use this node to store the name of it, otherwise we free it.
    if (currentNode == NULL)
    {
        StringCbPrintfExW(conductor->FileName, MAX_PATH, NULL, NULL, 0, L"%ls", szFirstFile);
        currentNode = conductor;
    }
    else
    {
        conductor = conductor->Prev;
        free(conductor->Next);
    }

    // link the last node with the first one to make the list circular
    conductor->Next = root;
    root->Prev = conductor;
    conductor = currentNode;

    free(codecInfo);

    return conductor;
}
Exemplo n.º 8
0
/* Lately, dirSpec appears to be (rightfully) unused. */
__private_extern__ CFMutableArrayRef _CFContentsOfDirectory(CFAllocatorRef alloc, char *dirPath, void *dirSpec, CFURLRef dirURL, CFStringRef matchingAbstractType) {
    CFMutableArrayRef files = NULL;
    Boolean releaseBase = false;
    CFIndex pathLength = dirPath ? strlen(dirPath) : 0;
    // MF:!!! Need to use four-letter type codes where appropriate.
    CFStringRef extension = (matchingAbstractType ? _CFCopyExtensionForAbstractType(matchingAbstractType) : NULL);
    CFIndex targetExtLen = (extension ? CFStringGetLength(extension) : 0);

#if DEPLOYMENT_TARGET_WINDOWS
    // This is a replacement for 'dirent' below, and also uses wchar_t to support unicode paths
    wchar_t extBuff[CFMaxPathSize];
    int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :(
    
    if (targetExtLen > 0) {
        CFIndex usedBytes = 0;
        CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), kCFStringEncodingUTF16, 0, false, (uint8_t *)extBuff, CFMaxPathLength, &usedBytes);
        targetExtLen = usedBytes / sizeof(wchar_t);
        extBuff[targetExtLen] = '\0';
        wchar_t *extBuffStr = (wchar_t *)extBuff;
        if (extBuffStr[0] == '.')
            extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example
        
        wchar_t *extBuffDotPtr = extBuffStr;
        while ((extBuffDotPtr = wcschr(extBuffStr, '.'))) { //find the next . in the extension...
            extBuffInteriorDotCount++;
            extBuffStr = extBuffDotPtr + 1;
        }
    }
    
    wchar_t pathBuf[CFMaxPathSize];
    
    if (!dirPath) {
        if (!_CFURLGetWideFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) {
            if (extension) CFRelease(extension);
            return NULL;
        }
        
        pathLength = wcslen(pathBuf);

    } else {
        // Convert dirPath to a wide representation and put it into our pathBuf
        // Get the real length of the string in UTF16 characters
        CFStringRef dirPathStr = CFStringCreateWithCString(kCFAllocatorSystemDefault, dirPath, kCFStringEncodingUTF8);
        CFIndex strLen = CFStringGetLength(dirPathStr);
        
        // Copy the string into the buffer and terminate
        CFStringGetCharacters(dirPathStr, CFRangeMake(0, strLen), (UniChar *)pathBuf);
        pathBuf[strLen] = 0;
        
        CFRelease(dirPathStr);
    }
    
    WIN32_FIND_DATAW  file;
    HANDLE handle;
    
    if (pathLength + 2 >= CFMaxPathLength) {
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }

    pathBuf[pathLength] = '\\';
    pathBuf[pathLength + 1] = '*';
    pathBuf[pathLength + 2] = '\0';
    handle = FindFirstFileW(pathBuf, (LPWIN32_FIND_DATAW)&file);
    if (INVALID_HANDLE_VALUE == handle) {
        pathBuf[pathLength] = '\0';
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }

    files = CFArrayCreateMutable(alloc, 0, &kCFTypeArrayCallBacks);

    do {
        CFURLRef fileURL;
        CFIndex namelen = wcslen(file.cFileName);
        if (file.cFileName[0] == '.' && (namelen == 1 || (namelen == 2  && file.cFileName[1] == '.'))) {
            continue;
        }

        if (targetExtLen > namelen) continue;    // if the extension is the same length or longer than the name, it can't possibly match.

        if (targetExtLen > 0) {
	    if (file.cFileName[namelen - 1] == '.') continue; //filename ends with a dot, no extension
	    
	    wchar_t *fileExt = NULL;
            
            if (extBuffInteriorDotCount == 0) {
                fileExt = wcsrchr(file.cFileName, '.');
            } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar"
                wchar_t *save = file.cFileName;
                while ((save = wcschr(save, '.')) && !fileExt) {
                    wchar_t *temp = save;
                    int moreDots = 0;
                    while ((temp = wcschr(temp, '.'))) {
                        if (++moreDots == extBuffInteriorDotCount) break;
                    }
                    if (moreDots == extBuffInteriorDotCount) {
                        fileExt = save;
                    }
                }
            }
	    
	    if (!fileExt) continue; //no extension
	    
	    if (((const wchar_t *)extBuff)[0] != '.')
		fileExt++; //omit the dot if the target file extension omits the dot
	    
	    CFIndex fileExtLen = wcslen(fileExt);
	    
	    //if the extensions are different lengths, they can't possibly match
	    if (fileExtLen != targetExtLen) continue;
	    
            // Check to see if it matches the extension we're looking for.
            if (_wcsicmp(fileExt, (const wchar_t *)extBuff) != 0) {
                continue;
            }
        }
	if (dirURL == NULL) {
	    CFStringRef dirURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)pathBuf, pathLength * sizeof(wchar_t), kCFStringEncodingUTF16, NO);
	    dirURL = CFURLCreateWithFileSystemPath(alloc, dirURLStr, kCFURLWindowsPathStyle, true);
	    CFRelease(dirURLStr);
            releaseBase = true;
        }
        // MF:!!! What about the trailing slash?
        CFStringRef fileURLStr = CFStringCreateWithBytes(alloc, (const uint8_t *)file.cFileName, namelen * sizeof(wchar_t), kCFStringEncodingUTF16, NO);
        fileURL = CFURLCreateWithFileSystemPathRelativeToBase(alloc, fileURLStr, kCFURLWindowsPathStyle, (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false, dirURL);
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
        CFRelease(fileURLStr);
    } while (FindNextFileW(handle, &file));
    FindClose(handle);
    pathBuf[pathLength] = '\0';

#elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
    uint8_t extBuff[CFMaxPathSize];
    int extBuffInteriorDotCount = 0; //people insist on using extensions like ".trace.plist", so we need to know how many dots back to look :(
    
    if (targetExtLen > 0) {
        CFStringGetBytes(extension, CFRangeMake(0, targetExtLen), CFStringFileSystemEncoding(), 0, false, extBuff, CFMaxPathLength, &targetExtLen);
        extBuff[targetExtLen] = '\0';
        char *extBuffStr = (char *)extBuff;
        if (extBuffStr[0] == '.')
            extBuffStr++; //skip the first dot, it's legitimate to have ".plist" for example
        
        char *extBuffDotPtr = extBuffStr;
        while ((extBuffDotPtr = strchr(extBuffStr, '.'))) { //find the next . in the extension...
            extBuffInteriorDotCount++;
            extBuffStr = extBuffDotPtr + 1;
        }
    }
    
    uint8_t pathBuf[CFMaxPathSize];
    
    if (!dirPath) {
        if (!CFURLGetFileSystemRepresentation(dirURL, true, pathBuf, CFMaxPathLength)) {
            if (extension) CFRelease(extension);
            return NULL;
        } else {
            dirPath = (char *)pathBuf;
            pathLength = strlen(dirPath);
        }
    }
    
    struct dirent buffer;
    struct dirent *dp;
    int err;
   
    int no_hang_fd = __CFProphylacticAutofsAccess ? open("/dev/autofs_nowait", 0) : -1;
 
    DIR *dirp = opendir(dirPath);
    if (!dirp) {
        if (extension) {
            CFRelease(extension);
        }
	if (-1 != no_hang_fd) close(no_hang_fd);
        return NULL;
        // raiseErrno("opendir", path);
    }
    files = CFArrayCreateMutable(alloc, 0, & kCFTypeArrayCallBacks);

    while((0 == readdir_r(dirp, &buffer, &dp)) && dp) {
        CFURLRef fileURL;
	unsigned namelen = strlen(dp->d_name);

        // skip . & ..; they cause descenders to go berserk
	if (dp->d_name[0] == '.' && (namelen == 1 || (namelen == 2 && dp->d_name[1] == '.'))) {
            continue;
        }
        
        if (targetExtLen > namelen) continue;    // if the extension is the same length or longer than the name, it can't possibly match.
                
        if (targetExtLen > 0) {
	    if (dp->d_name[namelen - 1] == '.') continue; //filename ends with a dot, no extension
	      
            char *fileExt = NULL;
            if (extBuffInteriorDotCount == 0) {
                fileExt = strrchr(dp->d_name, '.'); 
            } else { //find the Nth occurrence of . from the end of the string, to handle ".foo.bar"
                char *save = dp->d_name;
                while ((save = strchr(save, '.')) && !fileExt) {
                    char *temp = save;
                    int moreDots = 0;
                    while ((temp = strchr(temp, '.'))) {
                        if (++moreDots == extBuffInteriorDotCount) break;
                    }
                    if (moreDots == extBuffInteriorDotCount) {
                        fileExt = save;
                    }
                }
            }
	    
	    if (!fileExt) continue; //no extension
	    
	    if (((char *)extBuff)[0] != '.')
		fileExt++; //omit the dot if the target extension omits the dot; safe, because we checked to make sure it isn't the last character just before
	    
	    size_t fileExtLen = strlen(fileExt);
	    
	    //if the extensions are different lengths, they can't possibly match
	    if (fileExtLen != targetExtLen) continue;
	    
	    // Check to see if it matches the extension we're looking for.
            if (strncmp(fileExt, (char *)extBuff, fileExtLen) != 0) {
                continue;
            }
        }
        if (dirURL == NULL) {
            dirURL = CFURLCreateFromFileSystemRepresentation(alloc, (uint8_t *)dirPath, pathLength, true);
            releaseBase = true;
        }
        if (dp->d_type == DT_DIR || dp->d_type == DT_UNKNOWN || dp->d_type == DT_LNK || dp->d_type == DT_WHT) {
            Boolean isDir = (dp->d_type == DT_DIR);
            if (!isDir) {
                // Ugh; must stat.
                char subdirPath[CFMaxPathLength];
                struct statinfo statBuf;
                strlcpy(subdirPath, dirPath, sizeof(subdirPath));
                strlcat(subdirPath, "/", sizeof(subdirPath));
                strlcat(subdirPath, dp->d_name, sizeof(subdirPath));
                if (stat(subdirPath, &statBuf) == 0) {
                    isDir = ((statBuf.st_mode & S_IFMT) == S_IFDIR);
                }
            }
#if DEPLOYMENT_TARGET_LINUX
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, namelen, isDir, dirURL);
#else
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc, (uint8_t *)dp->d_name, dp->d_namlen, isDir, dirURL);
#endif
        } else {
#if DEPLOYMENT_TARGET_LINUX
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, namelen, false, dirURL);
#else
            fileURL = CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, (uint8_t *)dp->d_name, dp->d_namlen, false, dirURL);
#endif
        }
        CFArrayAppendValue(files, fileURL);
        CFRelease(fileURL);
    }
    err = closedir(dirp);
    if (-1 != no_hang_fd) close(no_hang_fd);
    if (err != 0) {
        CFRelease(files);
        if (releaseBase) {
            CFRelease(dirURL);
        }
        if (extension) {
            CFRelease(extension);
        }
        return NULL;
    }
    
#else
    
#error _CFContentsOfDirectory() unknown architecture, not implemented
    
#endif

    if (extension) {
        CFRelease(extension);
    }
    if (releaseBase) {
        CFRelease(dirURL);
    }
    return files;
}
Exemplo n.º 9
0
/* Recursively searches the directory dir for files that match the signature
 * sig, up to (depth + 1) levels deep.  That is, if depth is 0, it searches dir
 * (and only dir).  If depth is 1, searches dir and its immediate
 * subdirectories.
 * Assumes sig->File is not NULL.
 * Returns ERROR_SUCCESS on success (which may include non-critical errors),
 * something else on failures which should halt the install.
 */
static UINT ACTION_RecurseSearchDirectory(MSIPACKAGE *package, LPWSTR *appValue,
 MSISIGNATURE *sig, LPCWSTR dir, int depth)
{
    HANDLE hFind;
    WIN32_FIND_DATAW findData;
    UINT rc = ERROR_SUCCESS;
    size_t dirLen = lstrlenW(dir), fileLen = lstrlenW(sig->File);
    WCHAR subpath[MAX_PATH];
    WCHAR *buf;
    DWORD len;

    static const WCHAR starDotStarW[] = { '*','.','*',0 };

    TRACE("Searching directory %s for file %s, depth %d\n", debugstr_w(dir),
          debugstr_w(sig->File), depth);

    if (depth < 0)
        return ERROR_SUCCESS;

    *appValue = NULL;
    /* We need the buffer in both paths below, so go ahead and allocate it
     * here.  Add two because we might need to add a backslash if the dir name
     * isn't backslash-terminated.
     */
    len = dirLen + max(fileLen, strlenW(starDotStarW)) + 2;
    buf = msi_alloc(len * sizeof(WCHAR));
    if (!buf)
        return ERROR_OUTOFMEMORY;

    lstrcpyW(buf, dir);
    PathAddBackslashW(buf);
    lstrcatW(buf, sig->File);

    hFind = FindFirstFileW(buf, &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            BOOL matches;

            rc = ACTION_FileMatchesSig(sig, &findData, buf, &matches);
            if (rc == ERROR_SUCCESS && matches)
            {
                TRACE("found file, returning %s\n", debugstr_w(buf));
                *appValue = buf;
            }
        }
        FindClose(hFind);
    }

    if (rc == ERROR_SUCCESS && !*appValue)
    {
        lstrcpyW(buf, dir);
        PathAddBackslashW(buf);
        lstrcatW(buf, starDotStarW);

        hFind = FindFirstFileW(buf, &findData);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
                lstrcmpW(findData.cFileName, szDot) &&
                lstrcmpW(findData.cFileName, szDotDot))
            {
                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                rc = ACTION_RecurseSearchDirectory(package, appValue, sig,
                                                   subpath, depth - 1);
            }

            while (rc == ERROR_SUCCESS && !*appValue &&
                   FindNextFileW(hFind, &findData) != 0)
            {
                if (!lstrcmpW(findData.cFileName, szDot) ||
                    !lstrcmpW(findData.cFileName, szDotDot))
                    continue;

                lstrcpyW(subpath, dir);
                PathAppendW(subpath, findData.cFileName);
                if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                    rc = ACTION_RecurseSearchDirectory(package, appValue,
                                                       sig, subpath, depth - 1);
            }

            FindClose(hFind);
        }
    }

    if (*appValue != buf)
        msi_free(buf);

    return rc;
}
Exemplo n.º 10
0
HANDLE FindFile::Win32Find(HANDLE hFind,const char *Mask,const wchar *MaskW,struct FindData *fd)
{
#ifndef _WIN_CE
  if (WinNT())
#endif
  {
    wchar WideMask[NM];
    if (MaskW!=NULL && *MaskW!=0)
      strcpyw(WideMask,MaskW);
    else
      CharToWide(Mask,WideMask);

    WIN32_FIND_DATAW FindData;
    if (hFind==INVALID_HANDLE_VALUE)
    {
      hFind=FindFirstFileW(WideMask,&FindData);
      if (hFind==INVALID_HANDLE_VALUE)
      {
        int SysErr=GetLastError();
        fd->Error=(SysErr!=ERROR_FILE_NOT_FOUND &&
                   SysErr!=ERROR_PATH_NOT_FOUND &&
                   SysErr!=ERROR_NO_MORE_FILES);
      }
    }
    else
      if (!FindNextFileW(hFind,&FindData))
      {
        hFind=INVALID_HANDLE_VALUE;
        fd->Error=GetLastError()!=ERROR_NO_MORE_FILES;
      }

    if (hFind!=INVALID_HANDLE_VALUE)
    {
      strcpyw(fd->NameW,WideMask);
      strcpyw(PointToName(fd->NameW),FindData.cFileName);
      WideToChar(fd->NameW,fd->Name);
      fd->Size=int32to64(FindData.nFileSizeHigh,FindData.nFileSizeLow);
      fd->FileAttr=FindData.dwFileAttributes;
      WideToChar(FindData.cAlternateFileName,fd->ShortName);
      fd->ftCreationTime=FindData.ftCreationTime;
      fd->ftLastAccessTime=FindData.ftLastAccessTime;
      fd->ftLastWriteTime=FindData.ftLastWriteTime;
      fd->mtime=FindData.ftLastWriteTime;
      fd->ctime=FindData.ftCreationTime;
      fd->atime=FindData.ftLastAccessTime;
      fd->FileTime=fd->mtime.GetDos();

#ifndef _WIN_CE
      if (LowAscii(fd->NameW))
        *fd->NameW=0;
#endif
    }
  }
#ifndef _WIN_CE
  else
  {
    char CharMask[NM];
    if (Mask!=NULL && *Mask!=0)
      strcpy(CharMask,Mask);
    else
      WideToChar(MaskW,CharMask);

    WIN32_FIND_DATA FindData;
    if (hFind==INVALID_HANDLE_VALUE)
    {
      hFind=FindFirstFile(CharMask,&FindData);
      if (hFind==INVALID_HANDLE_VALUE)
      {
        int SysErr=GetLastError();
        fd->Error=SysErr!=ERROR_FILE_NOT_FOUND && SysErr!=ERROR_PATH_NOT_FOUND;
      }
    }
    else
      if (!FindNextFile(hFind,&FindData))
      {
        hFind=INVALID_HANDLE_VALUE;
        fd->Error=GetLastError()!=ERROR_NO_MORE_FILES;
      }

    if (hFind!=INVALID_HANDLE_VALUE)
    {
      strcpy(fd->Name,CharMask);
      strcpy(PointToName(fd->Name),FindData.cFileName);
      CharToWide(fd->Name,fd->NameW);
      fd->Size=int32to64(FindData.nFileSizeHigh,FindData.nFileSizeLow);
      fd->FileAttr=FindData.dwFileAttributes;
      strcpy(fd->ShortName,FindData.cAlternateFileName);
      fd->ftCreationTime=FindData.ftCreationTime;
      fd->ftLastAccessTime=FindData.ftLastAccessTime;
      fd->ftLastWriteTime=FindData.ftLastWriteTime;
      fd->mtime=FindData.ftLastWriteTime;
      fd->ctime=FindData.ftCreationTime;
      fd->atime=FindData.ftLastAccessTime;
      fd->FileTime=fd->mtime.GetDos();
      if (LowAscii(fd->Name))
        *fd->NameW=0;
    }
  }
#endif
  fd->Flags=0;
  return(hFind);
}
Exemplo n.º 11
0
ZtringList Dir::GetAllFileNames(const Ztring &Dir_Name_, dirlist_t Options)
{
    ZtringList ToReturn;
    Ztring Dir_Name=Dir_Name_;

    #ifdef ZENLIB_USEWX
        int Flags=wxDIR_FILES | wxDIR_DIRS;

        //Search for files
        wxArrayString Liste;
        wxFileName FullPath; FullPath=Dir_Name.c_str();
        //-File
        if (FullPath.FileExists())
        {
            FullPath.Normalize();
            Liste.Add(FullPath.GetFullPath());
        }
        //-Directory
        else if (FullPath.DirExists())
        {
            FullPath.Normalize();
            wxDir::GetAllFiles(FullPath.GetFullPath(), &Liste, Ztring(), Flags);
        }
        //-WildCards
        else
        {
            wxString FileName=FullPath.GetFullName();
            FullPath.SetFullName(Ztring()); //Supress filename
            FullPath.Normalize();
            if (FullPath.DirExists())
                wxDir::GetAllFiles(FullPath.GetPath(), &Liste, FileName, Flags);
        }

        //Compatible array
        ToReturn.reserve(Liste.GetCount());
        for (size_t Pos=0; Pos<Liste.GetCount(); Pos++)
            ToReturn.push_back(Liste[Pos].c_str());
    #else //ZENLIB_USEWX
        #ifdef WINDOWS
            //Is a dir?
            if (Exists(Dir_Name))
                Dir_Name+=_T("\\*");

            //Path
            Ztring Path=FileName::Path_Get(Dir_Name);
            if (Path.empty())
            {
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                    {
                        DWORD Path_Size=GetFullPathNameA(Dir_Name.To_Local().c_str(), 0, NULL, NULL);
                        char* PathTemp=new char[Path_Size+1];
                        if (GetFullPathNameA(Dir_Name.To_Local().c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                    {
                        DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                        Char* PathTemp=new Char[Path_Size+1];
                        if (GetFullPathNameW(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                            Path=FileName::Path_Get(PathTemp);
                        delete [] PathTemp; //PathTemp=NULL;
                    }
                #else
                    DWORD Path_Size=GetFullPathName(Dir_Name.c_str(), 0, NULL, NULL);
                    Char* PathTemp=new Char[Path_Size+1];
                    if (GetFullPathName(Dir_Name.c_str(), Path_Size+1, PathTemp, NULL))
                        Path=FileName::Path_Get(PathTemp);
                    delete [] PathTemp; //PathTemp=NULL;
                #endif //UNICODE
            }

            #ifdef UNICODE
                WIN32_FIND_DATAW FindFileDataW;
                HANDLE hFind;
                #ifndef ZENLIB_NO_WIN9X_SUPPORT
                WIN32_FIND_DATAA FindFileDataA;
                if (IsWin9X_Fast())
                    hFind=FindFirstFileA(Dir_Name.To_Local().c_str(), &FindFileDataA);
                else
                #endif //ZENLIB_NO_WIN9X_SUPPORT
                    hFind=FindFirstFileW(Dir_Name.c_str(), &FindFileDataW);
            #else
                WIN32_FIND_DATA FindFileData;
                HANDLE hFind=FindFirstFile(Dir_Name.c_str(), &FindFileData);
            #endif //UNICODE

            if (hFind==INVALID_HANDLE_VALUE)
                return ZtringList();

            BOOL ReturnValue;
            do
            {
                #ifdef UNICODE
                    Ztring File_Name;
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        File_Name=FindFileDataA.cFileName;
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        File_Name=FindFileDataW.cFileName;
                #else
                    Ztring File_Name(FindFileData.cFileName);
                #endif //UNICODE
                if (File_Name!=_T(".") && File_Name!=_T("..")) //Avoid . an ..
                {
                    Ztring File_Name_Complete=Path+_T("\\")+File_Name;
                    if (Exists(File_Name_Complete))
                    {
                        if (Options&Parse_SubDirs)
                            ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                    }
                    else if ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=_T('.')))
                        ToReturn.push_back(File_Name_Complete); //A file
                }
                #ifdef UNICODE
                    #ifndef ZENLIB_NO_WIN9X_SUPPORT
                    if (IsWin9X_Fast())
                        ReturnValue=FindNextFileA(hFind, &FindFileDataA);
                    else
                    #endif //ZENLIB_NO_WIN9X_SUPPORT
                        ReturnValue=FindNextFileW(hFind, &FindFileDataW);
                #else
                    ReturnValue=FindNextFile(hFind, &FindFileData);
                #endif //UNICODE
            }
            while (ReturnValue);

            FindClose(hFind);
        #else //WINDOWS
            //A file?
            if (File::Exists(Dir_Name))
            {
               ToReturn.push_back(Dir_Name); //TODO
               return ToReturn;
            }

            //A dir?
            if (!Dir::Exists(Dir_Name))
                return ToReturn; //Does not exist

            //open
            #ifdef UNICODE
                DIR* Dir=opendir(Dir_Name.To_Local().c_str());
            #else
                DIR* Dir=opendir(Dir_Name.c_str());
            #endif //UNICODE
            if (Dir)
            {
                //This is a dir
                //Normalizing dir (the / at the end)
                size_t Dir_Pos=Dir_Name.rfind(FileName_PathSeparator);
                if (Dir_Pos==std::string::npos)
                    Dir_Name+=FileName_PathSeparator;
                else if (Dir_Pos+Ztring(FileName_PathSeparator).size()!=Dir_Name.size())
                    Dir_Name+=FileName_PathSeparator;

                struct dirent *DirEnt;
                while((DirEnt=readdir(Dir))!=NULL)
                {
                    //A file
                    Ztring File_Name(DirEnt->d_name);
                    if (File_Name!=_T(".") && File_Name!=_T("..")) //Avoid . an ..
                    {
                        Ztring File_Name_Complete=Dir_Name+File_Name;
                        if (Exists(File_Name_Complete))
                        {
                            if (Options&Parse_SubDirs)
                                ToReturn+=GetAllFileNames(File_Name_Complete, Options); //A SubDir
                        }
                        else if ((Options&Include_Hidden) || (!File_Name.empty() && File_Name[0]!=_T('.')))
                            ToReturn.push_back(File_Name_Complete); //A file
                    }
                }

                //Close it
                closedir(Dir);
            }
            else
            {
                glob_t globbuf;
                if (glob(Dir_Name.To_Local().c_str(), GLOB_NOSORT, NULL, &globbuf)==0)
                {
                    for (int Pos=0; Pos<globbuf.gl_pathc; Pos++)
                        ToReturn.push_back(Ztring().From_Local(globbuf.gl_pathv[Pos]));
                }
            }
        #endif
    #endif //ZENLIB_USEWX

    return ToReturn;
}
Exemplo n.º 12
0
/*
 * WFP is Windows File Protection, in NT5 and Windows 2000 it maintains a cache
 * of known good dlls and scans through and replaces corrupted DLLs with these
 * known good versions. The only programs that should install into this dll
 * cache are Windows Updates and IE (which is treated like a Windows Update)
 *
 * Implementing this allows installing ie in win2k mode to actually install the
 * system dlls that we expect and need
 */
static int ProcessWindowsFileProtection(void)
{
    static const WCHAR winlogonW[] = {'S','o','f','t','w','a','r','e','\\',
                                      'M','i','c','r','o','s','o','f','t','\\',
                                      'W','i','n','d','o','w','s',' ','N','T','\\',
                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                      'W','i','n','l','o','g','o','n',0};
    static const WCHAR cachedirW[] = {'S','F','C','D','l','l','C','a','c','h','e','D','i','r',0};
    static const WCHAR dllcacheW[] = {'\\','d','l','l','c','a','c','h','e','\\','*',0};
    static const WCHAR wildcardW[] = {'\\','*',0};
    WIN32_FIND_DATAW finddata;
    HANDLE find_handle;
    BOOL find_rc;
    DWORD rc;
    HKEY hkey;
    LPWSTR dllcache = NULL;

    if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, winlogonW, &hkey ))
    {
        DWORD sz = 0;
        if (!RegQueryValueExW( hkey, cachedirW, 0, NULL, NULL, &sz))
        {
            sz += sizeof(WCHAR);
            dllcache = HeapAlloc(GetProcessHeap(),0,sz + sizeof(wildcardW));
            RegQueryValueExW( hkey, cachedirW, 0, NULL, (LPBYTE)dllcache, &sz);
            strcatW( dllcache, wildcardW );
        }
    }
    RegCloseKey(hkey);

    if (!dllcache)
    {
        DWORD sz = GetSystemDirectoryW( NULL, 0 );
        dllcache = HeapAlloc( GetProcessHeap(), 0, sz * sizeof(WCHAR) + sizeof(dllcacheW));
        GetSystemDirectoryW( dllcache, sz );
        strcatW( dllcache, dllcacheW );
    }

    find_handle = FindFirstFileW(dllcache,&finddata);
    dllcache[ strlenW(dllcache) - 2] = 0; /* strip off wildcard */
    find_rc = find_handle != INVALID_HANDLE_VALUE;
    while (find_rc)
    {
        static const WCHAR dotW[] = {'.',0};
        static const WCHAR dotdotW[] = {'.','.',0};
        WCHAR targetpath[MAX_PATH];
        WCHAR currentpath[MAX_PATH];
        UINT sz;
        UINT sz2;
        WCHAR tempfile[MAX_PATH];

        if (strcmpW(finddata.cFileName,dotW) == 0 || strcmpW(finddata.cFileName,dotdotW) == 0)
        {
            find_rc = FindNextFileW(find_handle,&finddata);
            continue;
        }

        sz = MAX_PATH;
        sz2 = MAX_PATH;
        VerFindFileW(VFFF_ISSHAREDFILE, finddata.cFileName, windowsdir,
                     windowsdir, currentpath, &sz, targetpath, &sz2);
        sz = MAX_PATH;
        rc = VerInstallFileW(0, finddata.cFileName, finddata.cFileName,
                             dllcache, targetpath, currentpath, tempfile, &sz);
        if (rc != ERROR_SUCCESS)
        {
            WINE_WARN("WFP: %s error 0x%x\n",wine_dbgstr_w(finddata.cFileName),rc);
            DeleteFileW(tempfile);
        }

        /* now delete the source file so that we don't try to install it over and over again */
        lstrcpynW( targetpath, dllcache, MAX_PATH - 1 );
        sz = strlenW( targetpath );
        targetpath[sz++] = '\\';
        lstrcpynW( targetpath + sz, finddata.cFileName, MAX_PATH - sz );
        if (!DeleteFileW( targetpath ))
            WINE_WARN( "failed to delete %s: error %u\n", wine_dbgstr_w(targetpath), GetLastError() );

        find_rc = FindNextFileW(find_handle,&finddata);
    }
    FindClose(find_handle);
    HeapFree(GetProcessHeap(),0,dllcache);
    return 1;
}
Exemplo n.º 13
0
bool Directory::read()
{
    if (!is_open())
    {
        return(false);
    }

#ifdef _MSC_VER
    while (!m_eof)
    {
        const std::wstring file_name(m_file.cFileName);
        const DWORD file_type = m_file.dwFileAttributes;
        m_eof = !FindNextFileW(m_dir, &m_file);

        if (L"." == file_name || L".." == file_name)
        {
            continue;
        }

        if (FILE_ATTRIBUTE_DIRECTORY == (FILE_ATTRIBUTE_DIRECTORY & file_type))
        {
            m_current_sub_path_short_name = unicode_to_utf8(file_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name + g_directory_separator;
            m_current_sub_path_is_directory = true;
        }
        else
        {
            m_current_sub_path_short_name = unicode_to_utf8(file_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name;
            m_current_sub_path_is_directory = false;
        }

        return(true);
    }
#else
    while (nullptr != m_file)
    {
        /*
         * do not do like this:
         *     struct dirent * file = m_file;
         *     m_file = readdir(m_dir);
         *     operate_function(file);
         * the behavior is undefined, the result is not expected
         */
        const std::string d_name(m_file->d_name);
#if 0
        const size_t d_type = m_file->d_type;
#endif // 0
        m_file = readdir(m_dir);

        if ("." == d_name || ".." == d_name)
        {
            continue;
        }

#if 0
        /*
         * d_type: not supported by all filesystem
         */
        if (DT_DIR == (DT_DIR & d_type))
        {
            m_current_sub_path_short_name = ansi_to_utf8(d_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name + g_directory_separator;
            m_current_sub_path_is_directory = true;
            return(true);
        }
        else if (DT_REG == (DT_REG & d_type))
        {
            m_current_sub_path_short_name = ansi_to_utf8(d_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name;
            m_current_sub_path_is_directory = false;
            return(true);
        }
#else
        stupid_stat_t stat_buf = { 0x00 };
        const std::string file_name(utf8_to_ansi(m_dir_name) + d_name);
        if (0 != stupid_stat(file_name.c_str(), &stat_buf))
        {
            continue;
        }

        if (S_IFDIR == (S_IFDIR & stat_buf.st_mode))
        {
            m_current_sub_path_short_name = ansi_to_utf8(d_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name + g_directory_separator;
            m_current_sub_path_is_directory = true;
            return(true);
        }
        else if (S_IFREG == (S_IFREG & stat_buf.st_mode))
        {
            m_current_sub_path_short_name = ansi_to_utf8(d_name);
            m_current_sub_path_name = m_dir_name + m_current_sub_path_short_name;
            m_current_sub_path_is_directory = false;
            return(true);
        }
#endif // 0
    }
#endif // _MSC_VER

    m_current_sub_path_short_name.clear();
    m_current_sub_path_name.clear();
    m_current_sub_path_is_directory = false;

    return(false);
}
Exemplo n.º 14
0
static int DeleteDirectory(wchar_t *refcstrRootDirectory)
{
    #define DEFAULT_PATTERN L"%s/*.*"
    BOOL bDeleteSubdirectories = TRUE;
    BOOL bSubdirectory = FALSE;
    HANDLE hFile;
    WIN32_FIND_DATAW FileInformation;
    DWORD dwError;
    wchar_t	*strPattern		= NULL;
    wchar_t	*strFilePath	= NULL;
    int len = 0;

    if (refcstrRootDirectory == NULL) return 1;

    len = (int)(wcslen(refcstrRootDirectory) + (int)wcslen(DEFAULT_PATTERN) + 1);

    strPattern = (wchar_t*)MALLOC(sizeof(wchar_t) * len);
    if (strPattern)
    {
        swprintf(strPattern, len, DEFAULT_PATTERN, refcstrRootDirectory);
    }
    else
    {
        return 1;
    }

    hFile = FindFirstFileW(strPattern, &FileInformation);
    if (strPattern) { FREE(strPattern);strPattern=NULL;}

    if(hFile != INVALID_HANDLE_VALUE)
    {
        do
        {
            if ( (wcscmp(FileInformation.cFileName,L".") != 0) && (wcscmp(FileInformation.cFileName,L"..") != 0) )
            {
                #define FORMAT_PATH_TO_REMOVE L"%s\\%s"
                int len = (int) (wcslen(refcstrRootDirectory) + wcslen(FORMAT_PATH_TO_REMOVE) + wcslen((wchar_t*)(FileInformation.cFileName)) + 1);
                strFilePath = (wchar_t*) MALLOC(sizeof(wchar_t) * len);
                if (strFilePath)
                {
                    swprintf(strFilePath, len, FORMAT_PATH_TO_REMOVE, refcstrRootDirectory, FileInformation.cFileName);
                }

                if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    if(bDeleteSubdirectories)
                    {
                        int iRC = DeleteDirectory(strFilePath);
                        if (strFilePath) {FREE(strFilePath); strFilePath = NULL;}
                        if (strPattern) {FREE(strPattern); strPattern = NULL;}

                        if(iRC) 
                        {
                            return iRC;
                        }
                    }
                    else bSubdirectory = TRUE;
                }
                else
                {
                    if(SetFileAttributesW(strFilePath,FILE_ATTRIBUTE_NORMAL) == FALSE) 
                    {
                        if (strFilePath) {FREE(strFilePath); strFilePath = NULL;}
                        if (strPattern) {FREE(strPattern); strPattern = NULL;}
                        return GetLastError();
                    }

                    if(DeleteFileW(strFilePath) == FALSE) 
                    {
                        if (strFilePath) {FREE(strFilePath); strFilePath = NULL;}
                        if (strPattern) {FREE(strPattern); strPattern = NULL;}
                        return GetLastError();
                    }
                }
            }
        } while(FindNextFileW(hFile, &FileInformation) == TRUE);

        FindClose(hFile);
        if (strFilePath) {FREE(strFilePath); strFilePath = NULL;}
        if (strPattern) {FREE(strPattern); strPattern = NULL;}

        dwError = GetLastError();
        if(dwError != ERROR_NO_MORE_FILES) 
        {
            return dwError;
        }
        else
        {
            if(!bSubdirectory)
            {
                if(SetFileAttributesW(refcstrRootDirectory,FILE_ATTRIBUTE_NORMAL) == FALSE) 
                {
                    return GetLastError();
                }
                if(RemoveDirectoryW(refcstrRootDirectory) == FALSE)	
                {
                    return GetLastError();
                }
            }
        }
    }

    if (strFilePath) {FREE(strFilePath); strFilePath = NULL;}
    if (strPattern) {FREE(strPattern); strPattern = NULL;}
    return 0;
}
Exemplo n.º 15
0
RTDECL(int) RTDirReadEx(PRTDIR pDir, PRTDIRENTRYEX pDirEntry, size_t *pcbDirEntry, RTFSOBJATTRADD enmAdditionalAttribs, uint32_t fFlags)
{
    /** @todo Symlinks: Find[First|Next]FileW will return info about
        the link, so RTPATH_F_FOLLOW_LINK is not handled correctly. */
    /*
     * Validate input.
     */
    if (!pDir || pDir->u32Magic != RTDIR_MAGIC)
    {
        AssertMsgFailed(("Invalid pDir=%p\n", pDir));
        return VERR_INVALID_PARAMETER;
    }
    if (!pDirEntry)
    {
        AssertMsgFailed(("Invalid pDirEntry=%p\n", pDirEntry));
        return VERR_INVALID_PARAMETER;
    }
    if (    enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
        ||  enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
    {
        AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
        return VERR_INVALID_PARAMETER;
    }
    AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
    size_t cbDirEntry = sizeof(*pDirEntry);
    if (pcbDirEntry)
    {
        cbDirEntry = *pcbDirEntry;
        if (cbDirEntry < RT_UOFFSETOF(RTDIRENTRYEX, szName[2]))
        {
            AssertMsgFailed(("Invalid *pcbDirEntry=%d (min %d)\n", *pcbDirEntry, RT_OFFSETOF(RTDIRENTRYEX, szName[2])));
            return VERR_INVALID_PARAMETER;
        }
    }

    /*
     * Fetch data?
     */
    if (!pDir->fDataUnread)
    {
        RTStrFree(pDir->pszName);
        pDir->pszName = NULL;

        BOOL fRc = FindNextFileW(pDir->hDir, &pDir->Data);
        if (!fRc)
        {
            int iErr = GetLastError();
            if (pDir->hDir == INVALID_HANDLE_VALUE || iErr == ERROR_NO_MORE_FILES)
                return VERR_NO_MORE_FILES;
            return RTErrConvertFromWin32(iErr);
        }
    }

    /*
     * Convert the filename to UTF-8.
     */
    if (!pDir->pszName)
    {
        int rc = RTUtf16ToUtf8((PCRTUTF16)pDir->Data.cFileName, &pDir->pszName);
        if (RT_FAILURE(rc))
        {
            pDir->pszName = NULL;
            return rc;
        }
        pDir->cchName = strlen(pDir->pszName);
    }

    /*
     * Check if we've got enough space to return the data.
     */
    const char  *pszName    = pDir->pszName;
    const size_t cchName    = pDir->cchName;
    const size_t cbRequired = RT_OFFSETOF(RTDIRENTRYEX, szName[1]) + cchName;
    if (pcbDirEntry)
        *pcbDirEntry = cbRequired;
    if (cbRequired > cbDirEntry)
        return VERR_BUFFER_OVERFLOW;

    /*
     * Setup the returned data.
     */
    pDir->fDataUnread  = false;
    pDirEntry->cbName  = (uint16_t)cchName;
    Assert(pDirEntry->cbName == cchName);
    memcpy(pDirEntry->szName, pszName, cchName + 1);
    if (pDir->Data.cAlternateFileName[0])
    {
        /* copy and calc length */
        PCRTUTF16 pwszSrc = (PCRTUTF16)pDir->Data.cAlternateFileName;
        PRTUTF16  pwszDst = pDirEntry->wszShortName;
        uint32_t  off = 0;
        while (off < RT_ELEMENTS(pDirEntry->wszShortName) - 1U && pwszSrc[off])
        {
            pwszDst[off] = pwszSrc[off];
            off++;
        }
        pDirEntry->cwcShortName = (uint16_t)off;

        /* zero the rest */
        do
            pwszDst[off++] = '\0';
        while (off < RT_ELEMENTS(pDirEntry->wszShortName));
    }
    else
    {
        memset(pDirEntry->wszShortName, 0, sizeof(pDirEntry->wszShortName));
        pDirEntry->cwcShortName = 0;
    }

    pDirEntry->Info.cbObject    = ((uint64_t)pDir->Data.nFileSizeHigh << 32)
                                |  (uint64_t)pDir->Data.nFileSizeLow;
    pDirEntry->Info.cbAllocated = pDirEntry->Info.cbObject;

    Assert(sizeof(uint64_t) == sizeof(pDir->Data.ftCreationTime));
    RTTimeSpecSetNtTime(&pDirEntry->Info.BirthTime,         *(uint64_t *)&pDir->Data.ftCreationTime);
    RTTimeSpecSetNtTime(&pDirEntry->Info.AccessTime,        *(uint64_t *)&pDir->Data.ftLastAccessTime);
    RTTimeSpecSetNtTime(&pDirEntry->Info.ModificationTime,  *(uint64_t *)&pDir->Data.ftLastWriteTime);
    pDirEntry->Info.ChangeTime  = pDirEntry->Info.ModificationTime;

    pDirEntry->Info.Attr.fMode  = rtFsModeFromDos((pDir->Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT,
                                                   pszName, cchName);

    /*
     * Requested attributes (we cannot provide anything actually).
     */
    switch (enmAdditionalAttribs)
    {
        case RTFSOBJATTRADD_EASIZE:
            pDirEntry->Info.Attr.enmAdditional          = RTFSOBJATTRADD_EASIZE;
            pDirEntry->Info.Attr.u.EASize.cb            = 0;
            break;

        case RTFSOBJATTRADD_UNIX:
            pDirEntry->Info.Attr.enmAdditional          = RTFSOBJATTRADD_UNIX;
            pDirEntry->Info.Attr.u.Unix.uid             = ~0U;
            pDirEntry->Info.Attr.u.Unix.gid             = ~0U;
            pDirEntry->Info.Attr.u.Unix.cHardlinks      = 1;
            pDirEntry->Info.Attr.u.Unix.INodeIdDevice   = 0; /** @todo Use the volume serial number (see GetFileInformationByHandle). */
            pDirEntry->Info.Attr.u.Unix.INodeId         = 0; /** @todo Use the fileid (see GetFileInformationByHandle). */
            pDirEntry->Info.Attr.u.Unix.fFlags          = 0;
            pDirEntry->Info.Attr.u.Unix.GenerationId    = 0;
            pDirEntry->Info.Attr.u.Unix.Device          = 0;
            break;

        case RTFSOBJATTRADD_NOTHING:
            pDirEntry->Info.Attr.enmAdditional          = RTFSOBJATTRADD_NOTHING;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            pDirEntry->Info.Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_OWNER;
            pDirEntry->Info.Attr.u.UnixOwner.uid        = ~0U;
            pDirEntry->Info.Attr.u.UnixOwner.szName[0]  = '\0'; /** @todo return something sensible here. */
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            pDirEntry->Info.Attr.enmAdditional          = RTFSOBJATTRADD_UNIX_GROUP;
            pDirEntry->Info.Attr.u.UnixGroup.gid        = ~0U;
            pDirEntry->Info.Attr.u.UnixGroup.szName[0]  = '\0';
            break;

        default:
            AssertMsgFailed(("Impossible!\n"));
            return VERR_INTERNAL_ERROR;
    }

    return VINF_SUCCESS;
}
Exemplo n.º 16
0
static HRESULT WINAPI EnumWorkItems_Next(IEnumWorkItems *iface, ULONG count, LPWSTR **names, ULONG *fetched)
{
    static const WCHAR tasksW[] = { '\\','T','a','s','k','s','\\','*',0 };
    EnumWorkItemsImpl *This = impl_from_IEnumWorkItems(iface);
    WCHAR path[MAX_PATH];
    WIN32_FIND_DATAW data;
    ULONG enumerated, allocated, dummy;
    LPWSTR *list;
    HRESULT hr = S_FALSE;

    TRACE("(%p)->(%u %p %p)\n", This, count, names, fetched);

    if (!count || !names || (!fetched && count > 1)) return E_INVALIDARG;

    if (!fetched) fetched = &dummy;

    *names = NULL;
    *fetched = 0;
    enumerated = 0;
    list = NULL;

    if (This->handle == INVALID_HANDLE_VALUE)
    {
        GetWindowsDirectoryW(path, MAX_PATH);
        lstrcatW(path, tasksW);
        This->handle = FindFirstFileW(path, &data);
        if (This->handle == INVALID_HANDLE_VALUE)
            return S_FALSE;
    }
    else
    {
        if (!FindNextFileW(This->handle, &data))
            return S_FALSE;
    }

    allocated = 64;
    list = CoTaskMemAlloc(allocated * sizeof(list[0]));
    if (!list) return E_OUTOFMEMORY;

    do
    {
        if (is_file(&data))
        {
            if (enumerated >= allocated)
            {
                LPWSTR *new_list;
                allocated *= 2;
                new_list = CoTaskMemRealloc(list, allocated * sizeof(list[0]));
                if (!new_list)
                {
                    hr = E_OUTOFMEMORY;
                    break;
                }
                list = new_list;
            }

            list[enumerated] = CoTaskMemAlloc((lstrlenW(data.cFileName) + 1) * sizeof(WCHAR));
            if (!list[enumerated])
            {
                hr = E_OUTOFMEMORY;
                break;
            }

            lstrcpyW(list[enumerated], data.cFileName);
            enumerated++;

            if (enumerated >= count)
            {
                hr = S_OK;
                break;
            }
        }
    } while (FindNextFileW(This->handle, &data));

    if (FAILED(hr))
        free_list(list, enumerated);
    else
    {
        *fetched = enumerated;
        *names = list;
    }

    return hr;
}
Exemplo n.º 17
0
static HRESULT DELNODE_recurse_dirtree(LPWSTR fname, DWORD flags)
{
    DWORD fattrs = GetFileAttributesW(fname);
    HRESULT ret = E_FAIL;

    static const WCHAR asterisk[] = {'*',0};
    static const WCHAR dot[] = {'.',0};
    static const WCHAR dotdot[] = {'.','.',0};

    if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
    {
        HANDLE hFindFile;
        WIN32_FIND_DATAW w32fd;
        BOOL done = TRUE;
        int fname_len = lstrlenW(fname);

        /* Generate a path with wildcard suitable for iterating */
        if (fname_len && fname[fname_len-1] != '\\') fname[fname_len++] = '\\';
        lstrcpyW(fname + fname_len, asterisk);

        if ((hFindFile = FindFirstFileW(fname, &w32fd)) != INVALID_HANDLE_VALUE)
        {
            /* Iterate through the files in the directory */
            for (done = FALSE; !done; done = !FindNextFileW(hFindFile, &w32fd))
            {
                TRACE("%s\n", debugstr_w(w32fd.cFileName));
                if (lstrcmpW(dot, w32fd.cFileName) != 0 &&
                    lstrcmpW(dotdot, w32fd.cFileName) != 0)
                {
                    lstrcpyW(fname + fname_len, w32fd.cFileName);
                    if (DELNODE_recurse_dirtree(fname, flags) != S_OK)
                    {
                        break; /* Failure */
                    }
                }
            }
            FindClose(hFindFile);
        }

        /* We're done with this directory, so restore the old path without wildcard */
        *(fname + fname_len) = '\0';

        if (done)
        {
            TRACE("%s: directory\n", debugstr_w(fname));
            if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && RemoveDirectoryW(fname))
            {
                ret = S_OK;
            }
        }
    }
    else
    {
        TRACE("%s: file\n", debugstr_w(fname));
        if (SetFileAttributesW(fname, FILE_ATTRIBUTE_NORMAL) && DeleteFileW(fname))
        {
            ret = S_OK;
        }
    }
    
    return ret;
}
Exemplo n.º 18
0
BOOL
EnumAvailableApplications(INT EnumType, AVAILENUMPROC lpEnumProc)
{
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAW FindFileData;
    WCHAR szPath[MAX_PATH];
    WCHAR szAppsPath[MAX_PATH];
    WCHAR szSectionLocale[MAX_PATH] = L"Section.";
    WCHAR szCabPath[MAX_PATH];
    WCHAR szLocale[4 + 1];
    APPLICATION_INFO Info;

    if (!GetCurrentDirectoryW(MAX_PATH, szPath))
    {
        return FALSE;
    }

    swprintf(szCabPath, L"%s\\rappmgr.cab", szPath);

    wcscat(szPath, L"\\rapps\\");
    wcscpy(szAppsPath, szPath);

    if (!CreateDirectory(szPath, NULL) &&
        GetLastError() != ERROR_ALREADY_EXISTS)
    {
        return FALSE;
    }

    GetLocaleInfoW(GetUserDefaultLCID(), LOCALE_ILANGUAGE, szLocale, sizeof(szLocale) / sizeof(WCHAR));
    wcscat(szSectionLocale, szLocale);

    wcscat(szPath, L"*.txt");

    hFind = FindFirstFileW(szPath, &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        if (GetFileAttributesW(szCabPath) == INVALID_FILE_ATTRIBUTES)
            DownloadApplicationsDB(APPLICATION_DATEBASE_URL);

        ExtractFilesFromCab(szCabPath, szAppsPath);
        hFind = FindFirstFileW(szPath, &FindFileData);
        if (hFind == INVALID_HANDLE_VALUE)
            return FALSE;
    }

#define GET_STRING1(a, b)  \
    if (!ParserGetString(szSectionLocale, a, b, MAX_PATH, FindFileData.cFileName)) \
        if (!ParserGetString(L"Section", a, b, MAX_PATH, FindFileData.cFileName)) \
            continue;

#define GET_STRING2(a, b)  \
    if (!ParserGetString(szSectionLocale, a, b, MAX_PATH, FindFileData.cFileName)) \
        if (!ParserGetString(L"Section", a, b, MAX_PATH, FindFileData.cFileName)) \
            b[0] = '\0';

    do
    {
        Info.Category = ParserGetInt(szSectionLocale, L"Category", FindFileData.cFileName);
        if (Info.Category == -1)
        {
            Info.Category = ParserGetInt(L"Section", L"Category", FindFileData.cFileName);
            if (Info.Category == -1)
                continue;
        }

        if (EnumType != Info.Category && EnumType != ENUM_ALL_AVAILABLE) continue;

        GET_STRING1(L"Name", Info.szName);
        GET_STRING1(L"URLDownload", Info.szUrlDownload);

        GET_STRING2(L"RegName", Info.szRegName);
        GET_STRING2(L"Version", Info.szVersion);
        GET_STRING2(L"Licence", Info.szLicence);
        GET_STRING2(L"Description", Info.szDesc);
        GET_STRING2(L"Size", Info.szSize);
        GET_STRING2(L"URLSite", Info.szUrlSite);
        GET_STRING2(L"CDPath", Info.szCDPath);

        if (!lpEnumProc(Info)) break;
    }
    while (FindNextFileW(hFind, &FindFileData) != 0);

    FindClose(hFind);

    return TRUE;
}
Exemplo n.º 19
0
UINT FileListFromDirectory(FILELIST **filelist,char *directory,BOOL *UserCancel)
{
	HANDLE hFindFile;
	WIN32_FIND_DATAW FindFileDataW;
	WIN32_FIND_DATAA FindFileDataA;
	BOOL RetVal=FALSE;
	BOOL KeepGoing;
	char *search;
	char *filename;
	char *name;
	LPWSTR wide;
	int widelen;
	int namelen;
	int retval;
	BOOL IsNT=FALSE;
	DWORD dwFileAttributes;
	OSVERSIONINFO osid;

	memset(&osid,0x00,sizeof(OSVERSIONINFO));

	osid.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
	GetVersionEx (&osid);   
	IsNT=(osid.dwPlatformId == VER_PLATFORM_WIN32_NT);

	if(directory[strlen(directory)-1]!='\\')
		strcat(directory,"\\");

	if(IsNT)
	{
		search=(char *)malloc(strlen("\\\\?\\")+strlen(directory)+strlen("*.*")+1);

		if(search==NULL)
			return TRUE;

		strcpy(search,"\\\\?\\");
		strcat(search,directory);
		strcat(search,"*.*");

		widelen=MultiByteToWideChar(_getmbcp(), 0, search, -1, 0,0);

		wide=(LPWSTR)malloc(widelen*sizeof(WCHAR));
		memset(wide,0x00,widelen*sizeof(WCHAR));

		retval=MultiByteToWideChar(_getmbcp(), 0, search,
			-1, wide,widelen);

		hFindFile=FindFirstFileW(wide,&FindFileDataW);
	
		free(wide);
		memset(search,0x00,sizeof(search));
		free(search);
	}
	else	
	{
		int bufsize;
		char shrtpath[MAX_PATH+1];

		bufsize=strlen(directory)+strlen("*.*")+1;

		GetShortPathName(directory,shrtpath,MAX_PATH);

		strcat(shrtpath,"*.*");

		hFindFile=FindFirstFileA(shrtpath,&FindFileDataA);

		memset(shrtpath,0x00,MAX_PATH);
	}

	if(hFindFile!=INVALID_HANDLE_VALUE)
	{
		RetVal=TRUE;

		while(RetVal==TRUE)
		{
			// Our quick fix callback to allow user to back out
			// of operation
			if(UserCancel!=NULL)
			{
				if(*UserCancel)
				{
					FindClose(hFindFile);
					return FALSE;
				}
			}

			if(IsNT)
			{
				namelen=WideCharToMultiByte(_getmbcp(), 0, FindFileDataW.cFileName,
					-1, 0,0,NULL,NULL);
				namelen++; // If we need to add directory slash

				name=(char *)malloc(namelen);
				memset(name,0x00,namelen);

				WideCharToMultiByte(_getmbcp(), 0, FindFileDataW.cFileName,
					-1, name,namelen,NULL,NULL);

				filename=(char *)malloc(strlen(directory)+namelen+1);

				strcpy(filename,directory);
				strcat(filename,name);

				dwFileAttributes=FindFileDataW.dwFileAttributes;
			}
			else
			{
				namelen=strlen(FindFileDataA.cFileName);
				namelen++;

				name=(char *)malloc(namelen);
				strcpy(name,FindFileDataA.cFileName);

				filename=(char *)malloc(strlen(directory)+namelen+1);
				strcpy(filename,directory);
				strcat(filename,name);

				dwFileAttributes=FindFileDataA.dwFileAttributes;
			}
	
			if((dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
				!=FILE_ATTRIBUTE_DIRECTORY)
			{
				FileListFromFile(filelist,filename,UserCancel);
			}
			else
			{
				if((strcmp(name,"."))&&
					(strcmp(name,"..")))
				{
					KeepGoing=FileListFromFile(filelist,filename,UserCancel);
					if(!KeepGoing)
					{
						FindClose(hFindFile);
						return FALSE;
					}

					(*filelist)->IsDirectory=TRUE;
					KeepGoing=FileListFromDirectory(filelist,filename,UserCancel);

					if(!KeepGoing)
					{
						FindClose(hFindFile);
						return FALSE;
					}
				}
			}

			memset(name,0x00,strlen(name));
			free(name);
			memset(filename,0x00,strlen(filename));
			free(filename);

			if(IsNT)
			{
				RetVal=FindNextFileW(hFindFile,&FindFileDataW);
			}
			else
			{
				RetVal=FindNextFileA(hFindFile,&FindFileDataA);
			}
		}

		FindClose(hFindFile);
	}

	return TRUE;
} 
Exemplo n.º 20
0
/*
 * __wt_win_directory_list --
 *	Get a list of files from a directory, MSVC version.
 */
int
__wt_win_directory_list(WT_FILE_SYSTEM *file_system,
    WT_SESSION *wt_session, const char *directory,
    const char *prefix, char ***dirlistp, uint32_t *countp)
{
	DWORD windows_error;
	HANDLE findhandle;
	WIN32_FIND_DATAW finddata;
	WT_DECL_ITEM(pathbuf);
	WT_DECL_ITEM(file_utf8);
	WT_DECL_ITEM(pathbuf_wide);
	WT_DECL_ITEM(prefix_wide);
	WT_DECL_RET;
	WT_SESSION_IMPL *session;
	size_t dirallocsz, pathlen, prefix_widelen;
	uint32_t count;
	char *dir_copy, **entries;

	session = (WT_SESSION_IMPL *)wt_session;

	*dirlistp = NULL;
	*countp = 0;

	findhandle = INVALID_HANDLE_VALUE;
	dirallocsz = 0;
	entries = NULL;

	WT_ERR(__wt_strdup(session, directory, &dir_copy));
	pathlen = strlen(dir_copy);
	if (dir_copy[pathlen - 1] == '\\')
		dir_copy[pathlen - 1] = '\0';
	WT_ERR(__wt_scr_alloc(session, pathlen + 3, &pathbuf));
	WT_ERR(__wt_buf_fmt(session, pathbuf, "%s\\*", dir_copy));

	WT_ERR(__wt_to_utf16_string(session, pathbuf->data, &pathbuf_wide));
	WT_ERR(__wt_to_utf16_string(session, prefix, &prefix_wide));
	prefix_widelen = wcslen(prefix_wide->data);

	findhandle = FindFirstFileW(pathbuf_wide->data, &finddata);
	if (findhandle == INVALID_HANDLE_VALUE) {
		windows_error = __wt_getlasterror();
		__wt_errx(session,
		    "%s: directory-list: FindFirstFile: %s",
		    pathbuf->data, __wt_formatmessage(session, windows_error));
		WT_ERR(__wt_map_windows_error(windows_error));
	}

	count = 0;
	do {
		/*
		 * Skip . and ..
		 */
		if (wcscmp(finddata.cFileName, L".") == 0 ||
		    wcscmp(finddata.cFileName, L"..") == 0)
			continue;

		/* The list of files is optionally filtered by a prefix. */
		if (prefix != NULL &&
		    wcsncmp(finddata.cFileName, prefix_wide->data,
			prefix_widelen) != 0)
			continue;

		WT_ERR(__wt_realloc_def(
		    session, &dirallocsz, count + 1, &entries));

		WT_ERR(__wt_to_utf8_string(
		    session, finddata.cFileName, &file_utf8));
		WT_ERR(__wt_strdup(session, file_utf8->data, &entries[count]));
		++count;
		__wt_scr_free(session, &file_utf8);
	} while (FindNextFileW(findhandle, &finddata) != 0);

	*dirlistp = entries;
	*countp = count;

err:	if (findhandle != INVALID_HANDLE_VALUE)
		if (FindClose(findhandle) == 0) {
			windows_error = __wt_getlasterror();
			__wt_errx(session,
			    "%s: directory-list: FindClose: %s",
			    pathbuf->data,
			    __wt_formatmessage(session, windows_error));
			if (ret == 0)
				ret = __wt_map_windows_error(windows_error);
		}

	__wt_free(session, dir_copy);
	__wt_scr_free(session, &pathbuf);
	__wt_scr_free(session, &file_utf8);
	__wt_scr_free(session, &pathbuf_wide);
	__wt_scr_free(session, &prefix_wide);

	if (ret == 0)
		return (0);

	WT_TRET(__wt_win_directory_list_free(
	    file_system, wt_session, entries, count));

	WT_RET_MSG(session, ret,
	    "%s: directory-list, prefix \"%s\"",
	    directory, prefix == NULL ? "" : prefix);
}
Exemplo n.º 21
0
// One large main method to keep this sample streamlined.
// 
// This function demonstrates how to start the .NET Core runtime,
// create an AppDomain, and execute managed code.
//
// It is meant as an educational sample, so not all error paths are checked,
// cross-platform functionality is not yet implemented, and some design
// decisions have been made to emphasize readability over efficiency.
int wmain(int argc, wchar_t* argv[])
{
	printf("Sample CoreCLR Host\n\n");

	//
	// STEP 1: Get the app to be run from the command line
	//
	if (argc < 2)
	{
		printf("ERROR - Specify exe to run as the app's first parameter");
		return -1;
	}

	// <Snippet1>
	// The managed application to run should be the first command-line parameter.
	// Subsequent command line parameters will be passed to the managed app later in this host.
	wchar_t targetApp[MAX_PATH];
	GetFullPathNameW(argv[1], MAX_PATH, targetApp, NULL);
	// </Snippet1>

	// Also note the directory the target app is in, as it will be referenced later.
	// The directory is determined by simply truncating the target app's full path
	// at the last path delimiter (\)
	wchar_t targetAppPath[MAX_PATH];
	wcscpy_s(targetAppPath, targetApp);
	size_t i = wcslen(targetAppPath - 1);
	while (i >= 0 && targetAppPath[i] != L'\\') i--;
	targetAppPath[i] = L'\0';



	//
	// STEP 2: Find and load CoreCLR.dll
	//
	HMODULE coreCLRModule;

	// Look in %CORE_ROOT%
	wchar_t coreRoot[MAX_PATH];
	size_t outSize;
	_wgetenv_s(&outSize, coreRoot, MAX_PATH, L"CORE_ROOT");
	coreCLRModule = LoadCoreCLR(coreRoot);

	// If CoreCLR.dll wasn't in %CORE_ROOT%, look next to the target app
	if (!coreCLRModule)
	{
		wcscpy_s(coreRoot, MAX_PATH, targetAppPath);
		coreCLRModule = LoadCoreCLR(coreRoot);
	}

	// If CoreCLR.dll wasn't in %CORE_ROOT% or next to the app, 
	// look in the common 1.1.0 install directory
	if (!coreCLRModule)
	{
		::ExpandEnvironmentStringsW(coreCLRInstallDirectory, coreRoot, MAX_PATH);
		coreCLRModule = LoadCoreCLR(coreRoot);
	}
	
	if (!coreCLRModule)
	{
		printf("ERROR - CoreCLR.dll could not be found");
		return -1;
	}
	else
	{
		wprintf(L"CoreCLR loaded from %s\n", coreRoot);
	}



	//
	// STEP 3: Get ICLRRuntimeHost2 instance
	//

	// <Snippet3>
	ICLRRuntimeHost2* runtimeHost;

	FnGetCLRRuntimeHost pfnGetCLRRuntimeHost =
		(FnGetCLRRuntimeHost)::GetProcAddress(coreCLRModule, "GetCLRRuntimeHost");

	if (!pfnGetCLRRuntimeHost)
	{
		printf("ERROR - GetCLRRuntimeHost not found");
		return -1;
	}

	// Get the hosting interface
	HRESULT hr = pfnGetCLRRuntimeHost(IID_ICLRRuntimeHost2, (IUnknown**)&runtimeHost);
	// </Snippet3>

	if (FAILED(hr))
	{
		printf("ERROR - Failed to get ICLRRuntimeHost2 instance.\nError code:%x\n", hr);
		return -1;
	}

	//
	// STEP 4: Set desired startup flags and start the CLR
	//

	// <Snippet4>
	hr = runtimeHost->SetStartupFlags(
		// These startup flags control runtime-wide behaviors.
		// A complete list of STARTUP_FLAGS can be found in mscoree.h,
		// but some of the more common ones are listed below.
		static_cast<STARTUP_FLAGS>(
			// STARTUP_FLAGS::STARTUP_SERVER_GC |								// Use server GC
			// STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN |		// Maximize domain-neutral loading
			// STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST |	// Domain-neutral loading for strongly-named assemblies
			STARTUP_FLAGS::STARTUP_CONCURRENT_GC |						// Use concurrent GC
			STARTUP_FLAGS::STARTUP_SINGLE_APPDOMAIN |					// All code executes in the default AppDomain 
																		// (required to use the runtimeHost->ExecuteAssembly helper function)
			STARTUP_FLAGS::STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN	// Prevents domain-neutral loading
		)
	);
	// </Snippet4>

	if (FAILED(hr))
	{
		printf("ERROR - Failed to set startup flags.\nError code:%x\n", hr);
		return -1;
	}

	// Starting the runtime will initialize the JIT, GC, loader, etc.
	hr = runtimeHost->Start();
	if (FAILED(hr))
	{
		printf("ERROR - Failed to start the runtime.\nError code:%x\n", hr);
		return -1;
	}
	else
	{
		printf("Runtime started\n");
	}



	//
	// STEP 5: Prepare properties for the AppDomain we will create
	//

	// Flags
	// <Snippet5>
	int appDomainFlags =
		// APPDOMAIN_FORCE_TRIVIAL_WAIT_OPERATIONS |		// Do not pump messages during wait
		// APPDOMAIN_SECURITY_SANDBOXED |					// Causes assemblies not from the TPA list to be loaded as partially trusted
		APPDOMAIN_ENABLE_PLATFORM_SPECIFIC_APPS |			// Enable platform-specific assemblies to run
		APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP |	// Allow PInvoking from non-TPA assemblies
		APPDOMAIN_DISABLE_TRANSPARENCY_ENFORCEMENT;			// Entirely disables transparency checks 
	// </Snippet5>

	// <Snippet6>
	// TRUSTED_PLATFORM_ASSEMBLIES
	// "Trusted Platform Assemblies" are prioritized by the loader and always loaded with full trust.
	// A common pattern is to include any assemblies next to CoreCLR.dll as platform assemblies.
	// More sophisticated hosts may also include their own Framework extensions (such as AppDomain managers)
	// in this list.
	int tpaSize = 100 * MAX_PATH; // Starting size for our TPA (Trusted Platform Assemblies) list
	wchar_t* trustedPlatformAssemblies = new wchar_t[tpaSize];
	trustedPlatformAssemblies[0] = L'\0';

	// Extensions to probe for when finding TPA list files
	wchar_t *tpaExtensions[] = {
		L"*.dll",
		L"*.exe",
		L"*.winmd"
	};

	// Probe next to CoreCLR.dll for any files matching the extensions from tpaExtensions and
	// add them to the TPA list. In a real host, this would likely be extracted into a separate function
	// and perhaps also run on other directories of interest.
	for (int i = 0; i < _countof(tpaExtensions); i++)
	{
		// Construct the file name search pattern
		wchar_t searchPath[MAX_PATH];
		wcscpy_s(searchPath, MAX_PATH, coreRoot);
		wcscat_s(searchPath, MAX_PATH, L"\\");
		wcscat_s(searchPath, MAX_PATH, tpaExtensions[i]);

		// Find files matching the search pattern
		WIN32_FIND_DATAW findData;
		HANDLE fileHandle = FindFirstFileW(searchPath, &findData);

		if (fileHandle != INVALID_HANDLE_VALUE)
		{
			do
			{
				// Construct the full path of the trusted assembly
				wchar_t pathToAdd[MAX_PATH];
				wcscpy_s(pathToAdd, MAX_PATH, coreRoot);
				wcscat_s(pathToAdd, MAX_PATH, L"\\");
				wcscat_s(pathToAdd, MAX_PATH, findData.cFileName);

				// Check to see if TPA list needs expanded
				if (wcslen(pathToAdd) + (3) + wcslen(trustedPlatformAssemblies) >= tpaSize)
				{
					// Expand, if needed
					tpaSize *= 2;
					wchar_t* newTPAList = new wchar_t[tpaSize];
					wcscpy_s(newTPAList, tpaSize, trustedPlatformAssemblies);
					trustedPlatformAssemblies = newTPAList;
				}

				// Add the assembly to the list and delimited with a semi-colon
				wcscat_s(trustedPlatformAssemblies, tpaSize, pathToAdd);
				wcscat_s(trustedPlatformAssemblies, tpaSize, L";");

				// Note that the CLR does not guarantee which assembly will be loaded if an assembly
				// is in the TPA list multiple times (perhaps from different paths or perhaps with different NI/NI.dll
				// extensions. Therefore, a real host should probably add items to the list in priority order and only
				// add a file if it's not already present on the list.
				//
				// For this simple sample, though, and because we're only loading TPA assemblies from a single path,
				// we can ignore that complication.
			}
			while (FindNextFileW(fileHandle, &findData));
			FindClose(fileHandle);
		}
	}


	// APP_PATHS
	// App paths are directories to probe in for assemblies which are not one of the well-known Framework assemblies
	// included in the TPA list.
	//
	// For this simple sample, we just include the directory the target application is in.
	// More complex hosts may want to also check the current working directory or other
	// locations known to contain application assets.
	wchar_t appPaths[MAX_PATH * 50];

	// Just use the targetApp provided by the user and remove the file name
	wcscpy_s(appPaths, targetAppPath);


	// APP_NI_PATHS
	// App (NI) paths are the paths that will be probed for native images not found on the TPA list. 
	// It will typically be similar to the app paths.
	// For this sample, we probe next to the app and in a hypothetical directory of the same name with 'NI' suffixed to the end.
	wchar_t appNiPaths[MAX_PATH * 50];
	wcscpy_s(appNiPaths, targetAppPath);
	wcscat_s(appNiPaths, MAX_PATH * 50, L";");
	wcscat_s(appNiPaths, MAX_PATH * 50, targetAppPath);
	wcscat_s(appNiPaths, MAX_PATH * 50, L"NI");


	// NATIVE_DLL_SEARCH_DIRECTORIES
	// Native dll search directories are paths that the runtime will probe for native DLLs called via PInvoke
	wchar_t nativeDllSearchDirectories[MAX_PATH * 50];
	wcscpy_s(nativeDllSearchDirectories, appPaths);
	wcscat_s(nativeDllSearchDirectories, MAX_PATH * 50, L";");
	wcscat_s(nativeDllSearchDirectories, MAX_PATH * 50, coreRoot);


	// PLATFORM_RESOURCE_ROOTS
	// Platform resource roots are paths to probe in for resource assemblies (in culture-specific sub-directories)
	wchar_t platformResourceRoots[MAX_PATH * 50];
	wcscpy_s(platformResourceRoots, appPaths);


	// AppDomainCompatSwitch
	// Specifies compatibility behavior for the app domain. This indicates which compatibility
	// quirks to apply if an assembly doesn't have an explicit Target Framework Moniker. If a TFM is
	// present on an assembly, the runtime will always attempt to use quirks appropriate to the version
	// of the TFM.
	// 
	// Typically the latest behavior is desired, but some hosts may want to default to older Silverlight
	// or Windows Phone behaviors for compatibility reasons.
	wchar_t* appDomainCompatSwitch = L"UseLatestBehaviorWhenTFMNotSpecified";
	// </Snippet6>


	//
	// STEP 6: Create the AppDomain
	//

	// <Snippet7>
	DWORD domainId;

	// Setup key/value pairs for AppDomain  properties
	const wchar_t* propertyKeys[] = {
		L"TRUSTED_PLATFORM_ASSEMBLIES",
		L"APP_PATHS",
		L"APP_NI_PATHS",
		L"NATIVE_DLL_SEARCH_DIRECTORIES",
		L"PLATFORM_RESOURCE_ROOTS",
		L"AppDomainCompatSwitch"
	};

	// Property values which were constructed in step 5
	const wchar_t* propertyValues[] = {
		trustedPlatformAssemblies,
		appPaths,
		appNiPaths,
		nativeDllSearchDirectories,
		platformResourceRoots,
		appDomainCompatSwitch
	};

	// Create the AppDomain
	hr = runtimeHost->CreateAppDomainWithManager(
		L"Sample Host AppDomain",		// Friendly AD name
		appDomainFlags,
		NULL,							// Optional AppDomain manager assembly name
		NULL,							// Optional AppDomain manager type (including namespace)
		sizeof(propertyKeys)/sizeof(wchar_t*),
		propertyKeys,
		propertyValues,
		&domainId);
	// </Snippet7>

	if (FAILED(hr))
	{
		printf("ERROR - Failed to create AppDomain.\nError code:%x\n", hr);
		return -1;
	}
	else
	{
		printf("AppDomain %d created\n\n", domainId);
	}



	//
	// STEP 7: Run managed code
	//

	// ExecuteAssembly will load a managed assembly and execute its entry point.
	wprintf(L"Executing %s...\n\n", targetApp);

	// <Snippet8>
	DWORD exitCode = -1;
	hr = runtimeHost->ExecuteAssembly(domainId, targetApp, argc - 1, (LPCWSTR*)(argc > 1 ? &argv[1] : NULL), &exitCode);
	// </Snippet8>

	if (FAILED(hr))
	{
		wprintf(L"ERROR - Failed to execute %s.\nError code:%x\n", targetApp, hr);
		return -1;
	}

	// Alternatively, to start managed code execution with a method other than an assembly's entrypoint,
	// runtimeHost->CreateDelegate can be used to create a pointer to an arbitrary static managed method
	// which can then be executed directly or via runtimeHost->ExecuteInAppDomain.
	//
	//  void *pfnDelegate = NULL;
	//  hr = runtimeHost->CreateDelegate(
	//	  domainId,
	//	  L"HW, Version=1.0.0.0, Culture=neutral",	// Target managed assembly
	//	  L"ConsoleApplication.Program",				// Target managed type
	//	  L"Main",									// Target entry point (static method)
	//	  (INT_PTR*)&pfnDelegate);
	//  if (FAILED(hr))
	//  {
	//	  printf("ERROR - Failed to create delegate.\nError code:%x\n", hr);
	//	  return -1;
	//  }
	//  ((MainMethodFp*)pfnDelegate)(NULL);



	//
	// STEP 8: Clean up
	//

	// <Snippet9>
	runtimeHost->UnloadAppDomain(domainId, true /* Wait until unload complete */);
	runtimeHost->Stop();
	runtimeHost->Release();
	// </Snippet9>

	printf("\nDone\n");

	return exitCode;
}
Exemplo n.º 22
0
static void DoTest(const WCHAR* szwDir, 
                   const WCHAR* szwResult1, 
                   const WCHAR* szwResult2)
{
    HANDLE hFind;
    WIN32_FIND_DATAW findFileData;

    /*
    ** find the first
    */
    if ((hFind = FindFirstFileW(szwDir, &findFileData)) == INVALID_HANDLE_VALUE)
    {
        Fail("FindNextFileW: ERROR -> FindFirstFileW(\"%S\") failed. "
            "GetLastError returned %u.\n", 
            szwStar,
            GetLastError());
    }

    /* did we find the expected */
    if (wcscmp(szwResult1, findFileData.cFileName) != 0)
    {
        if (!FindClose(hFind))
        {
            Trace("FindNextFileW: ERROR -> Failed to close the find handle. "
                "GetLastError returned %u.\n",
                GetLastError());
        }
        Fail("FindNextFileW: ERROR -> FindFirstFile(\"%S\") didn't find"
            " the expected \"%S\" but found \"%S\" instead.\n",
            szwDir,
            szwResult1,
            findFileData.cFileName);
    }

    /* we found the first expected, let's see if we find the next expected*/
    if (!FindNextFileW(hFind, &findFileData))
    {
        Trace("FindNextFileW: ERROR -> FindNextFileW should have found \"%S\"" 
            " but failed. GetLastError returned %u.\n",
            szwResult2,
            GetLastError());
        if (!FindClose(hFind))
        {
            Trace("FindNextFileW: ERROR -> Failed to close the find handle. "
                "GetLastError returned %u.\n",
                GetLastError());
        }
        Fail("");
    }

    /* we found something, but was it '.' */
    if (wcscmp(szwResult2, findFileData.cFileName) != 0)
    {
        if (!FindClose(hFind))
        {
            Trace("FindNextFileW: ERROR -> Failed to close the find handle. "
                "GetLastError returned %u.\n",
                GetLastError());
        }
        Fail("FindNextFileW: ERROR -> FindNextFileW based on \"%S\" didn't find"
            " the expected \"%S\" but found \"%S\" instead.\n",
            szwDir,
            szwResult2,
            findFileData.cFileName);
    }
}
Exemplo n.º 23
0
// ---
tERROR pr_call LoaderData::find_modules_in_folder( const tVOID* param_pool, tDWORD param_pool_size, tCODEPAGE cp ) {

  tERROR  error = errOK;
  cStrObj path;

  if ( param_pool && param_pool_size )
    path.assign( param_pool, cp );
  else
    path.assign( ::g_plugins_path, cCP );

  PR_TRACE(( this, prtNOTIFY, "ldr\tSearch folder is \"%tS\"", path.data() ));

	#if !defined(NOT_VERIFY) && !defined(LATE_CHECK) && defined(NEW_SIGN_LIB)
		
		cSCheckList* list;
		error = sysCreateObjectQuick( (hOBJECT*)&list, IID_SCHECKLIST );
		if ( PR_SUCC(error) ) {
			tUINT  err_count   = 0;
			tUINT  loads_count = 0;
			tUINT  files_count = 0;
			cDSKMObjParams* par;
			path.add_path_sect( L"*.ppl", cCP_UNICODE );
				
			cStrBuff mask( path, cp );
			error = list->AddObjByMask( 0, &files_count, mask, cp );

			if ( PR_SUCC(error) ) {
				tDWORD id = 0;

				PR_TRACE(( this, prtIMPORTANT, "ldr\tmodules loading" ));
				_check_list( 0, list, 0 );
				PR_TRACE(( this, prtIMPORTANT, "ldr\tmodules loading, phase 2" ));

				error = list->GetFirstObjId( &id );
				while( PR_SUCC(error) && files_count ) {
					tDWORD dskm_err = DSKM_ERR_OK;
					tDWORD dskm_err_size( sizeof(dskm_err) );
					tDWORD par_size( sizeof(par) );

					--files_count;

					list->GetObjProp( id, DSKM_OBJ_PROCESSING_ERROR, &dskm_err, &dskm_err_size );

					if ( DSKM_NOT_OK(dskm_err) ) {
						dskm_err = DSKM_ERR_OK;
						list->GetObjProp( id, DSKM_OBJ_EXTERNAL_PARAM_PTR, &par, &par_size );
						++err_count;
					}
					else if ( PR_FAIL(list->GetObjProp(id,DSKM_OBJ_EXTERNAL_PARAM_PTR,&par,&par_size)) || !par->m_name_size )
						++err_count;
					else if ( PR_FAIL(create_module(par->m_name,par->m_name_size,par->m_name_cp)) )
						++err_count;
					else
						++loads_count;
					error = list->GetNextObjId( &id, id );
				}
				if ( error == errEND_OF_THE_LIST )
					error = errOK;
				PR_TRACE(( this, prtIMPORTANT, "ldr\tmodules loaded, files=%d, loads=%d, err=%d", err_count+loads_count, loads_count, err_count ));
			}

			list->sysCloseObject();
		}

	#else

		HANDLE           fh;
		cStrObj          mask( path );
		WIN32_FIND_DATAW fd;
		
		mask.add_path_sect( L"*.ppl", cCP_UNICODE );
		memset( &fd, 0, sizeof(fd) );
		
		cStrBuff name( mask, cp );

		PR_TRACE(( this, prtIMPORTANT, "ldr\tmodules loading." ));
		if ( cp == cCP_UNICODE )
			fh = FindFirstFileW( (LPCWSTR)(tWCHAR*)name, &fd );
		else
			fh = FindFirstFileA( (tCHAR*)name, (WIN32_FIND_DATA*)&fd );
		
		if ( fh && (fh != INVALID_HANDLE_VALUE) ) {
			
			BOOL res;
			
			do {
				tERROR err;
				cStrObj curr = path;
				curr.add_path_sect( fd.cFileName, cp );
				
				cStrBuff name( curr, cp );
				err = create_module( name, name.used(), cp );
				
				if ( PR_SUCC(error) && PR_FAIL(err) )
					error = err;
				
				if ( cp == cCP_UNICODE )
					res = FindNextFileW( fh, &fd );
				else
					res = FindNextFileA( fh, (WIN32_FIND_DATA*)&fd );
			} while( res );
			
			if ( PR_FAIL(error) ) {
				PR_TRACE(( this, prtERROR, "ldr\tError finding modules - %terr", error ));
			}
			
			FindClose( fh );
		}
		else {
			error = errMODULE_NOT_FOUND;
			PR_TRACE(( this, prtERROR, "ldr\tFolder has no prague modules" ));
		}
		PR_TRACE(( this, prtIMPORTANT, "ldr\tmodules loaded." ));
	#endif

	return error;
}
Exemplo n.º 24
0
/**************************************************************************
 *  CreateFolderEnumList()
 */
BOOL CreateFolderEnumList(
	IEnumIDList *list,
	LPCWSTR lpszPath,
	DWORD dwFlags)
{
    LPITEMIDLIST pidl=NULL;
    WIN32_FIND_DATAW stffile;
    HANDLE hFile;
    WCHAR  szPath[MAX_PATH];
    BOOL succeeded = TRUE;
    static const WCHAR stars[] = { '*','.','*',0 };
    static const WCHAR dot[] = { '.',0 };
    static const WCHAR dotdot[] = { '.','.',0 };

    TRACE("(%p)->(path=%s flags=0x%08x)\n", list, debugstr_w(lpszPath), dwFlags);

    if(!lpszPath || !lpszPath[0]) return FALSE;

    strcpyW(szPath, lpszPath);
    PathAddBackslashW(szPath);
    strcatW(szPath,stars);

    hFile = FindFirstFileW(szPath,&stffile);
    if ( hFile != INVALID_HANDLE_VALUE )
    {
        BOOL findFinished = FALSE;

        do
        {
            if ( !(stffile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) 
             || (dwFlags & SHCONTF_INCLUDEHIDDEN) )
            {
                if ( (stffile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
                 dwFlags & SHCONTF_FOLDERS &&
                 strcmpW(stffile.cFileName, dot) && strcmpW(stffile.cFileName, dotdot))
                {
                    pidl = _ILCreateFromFindDataW(&stffile);
                    succeeded = succeeded && AddToEnumList(list, pidl);
                }
                else if (!(stffile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                 && dwFlags & SHCONTF_NONFOLDERS)
                {
                    pidl = _ILCreateFromFindDataW(&stffile);
                    succeeded = succeeded && AddToEnumList(list, pidl);
                }
            }
            if (succeeded)
            {
                if (!FindNextFileW(hFile, &stffile))
                {
                    if (GetLastError() == ERROR_NO_MORE_FILES)
                        findFinished = TRUE;
                    else
                        succeeded = FALSE;
                }
            }
        } while (succeeded && !findFinished);
        FindClose(hFile);
    }
    return succeeded;
}
Exemplo n.º 25
0
/**
	sys_read_dir : string -> string list
	<doc>Return the content of a directory</doc>
**/
static value sys_read_dir( value p) {
	val_check(p,string);

        value result = alloc_array(0);
#ifdef HX_WINRT
   auto folder = (Windows::Storage::StorageFolder::GetFolderFromPathAsync( ref new Platform::String(val_wstring(p)) ))->GetResults();
   auto results = folder->GetFilesAsync(Windows::Storage::Search::CommonFileQuery::DefaultQuery)->GetResults();
   for(int i=0;i<results->Size;i++)
      val_array_push(result,alloc_wstring(results->GetAt(i)->Path->Data()));

#elif defined(NEKO_WINDOWS)
	const wchar_t *path = val_wstring(p);
	size_t len = wcslen(path);
   if (len>MAX_PATH)
      return alloc_null();

	WIN32_FIND_DATAW d;
	HANDLE handle;
	buffer b;
   wchar_t searchPath[ MAX_PATH + 4 ];
   memcpy(searchPath,path, len*sizeof(wchar_t));


	if( len && path[len-1] != '/' && path[len-1] != '\\' )
      searchPath[len++] = '/';
   searchPath[len++] = '*';
   searchPath[len++] = '.';
   searchPath[len++] = '*';
   searchPath[len] = '\0';

	gc_enter_blocking();
	handle = FindFirstFileW(searchPath,&d);
	if( handle == INVALID_HANDLE_VALUE )
	{
		gc_exit_blocking();
		return alloc_null();
	}
	while( true ) {
		// skip magic dirs
		if( d.cFileName[0] != '.' || (d.cFileName[1] != 0 && (d.cFileName[1] != '.' || d.cFileName[2] != 0)) ) {
		   gc_exit_blocking();
			val_array_push(result,alloc_wstring(d.cFileName));
			gc_enter_blocking();
		}
		if( !FindNextFileW(handle,&d) )
			break;
	}
	FindClose(handle);
	gc_exit_blocking();
#elif !defined(EPPC)
	DIR *d;
	struct dirent *e;
   const char *name = val_string(p);
	gc_enter_blocking();
	d = opendir(name);
	if( d == NULL )
	{
		gc_exit_blocking();
      val_throw(alloc_string("Invalid directory"));
	}
	while( true ) {
		e = readdir(d);
		if( e == NULL )
			break;
		// skip magic dirs
		if( e->d_name[0] == '.' && (e->d_name[1] == 0 || (e->d_name[1] == '.' && e->d_name[2] == 0)) )
			continue;
		gc_exit_blocking();
		val_array_push(result, alloc_string(e->d_name) );
		gc_enter_blocking();
	}
	closedir(d);
#endif
	gc_exit_blocking();
	return result;
}
Exemplo n.º 26
0
/*
 * Arguments: dir_udata, directory (string)
 *
 * Returns: [filename (string), is_directory (boolean)]
 * |
 * Returns (win32): [drive_letter (string: A: .. Z:), drive_type (string)]
 */
static int
sys_dir_next (lua_State *L)
{
  struct dir *dp = checkudata(L, 1, DIR_TYPENAME);

  if (lua_gettop(L) == 2) {  /* 'for' start? */
    /* return generator (dir_udata) */
    lua_pushvalue(L, 1);
    return sys_dir_open(L, 2, dp);
  } else {  /* 'for' step */
    char *filename;

#ifndef _WIN32
    struct dirent *entry;

    if (!dp->data)
      return 0;
    do {
      sys_vm_leave(L);
      entry = readdir(dp->data);
      sys_vm_enter(L);

      if (!entry) {
        closedir(dp->data);
        dp->data = NULL;
        return 0;
      }
      filename = entry->d_name;
    } while (filename[0] == '.' && (filename[1] == '\0'
     || (filename[1] == '.' && filename[2] == '\0')));

    lua_pushstring(L, filename);
    lua_pushboolean(L, entry->d_type & DT_DIR);
    return 2;
#else
    filename = (char *) dp->data.cFileName;

    if (dp->is_root) {
      while (++*filename <= 'Z') {
        const char *type;

        switch (GetDriveTypeA(filename)) {
        case DRIVE_REMOVABLE: type = "removable"; break;
        case DRIVE_FIXED: type = "fixed"; break;
        case DRIVE_REMOTE: type = "remote"; break;
        case DRIVE_CDROM: type = "cdrom"; break;
        case DRIVE_RAMDISK: type = "ramdisk"; break;
        default: continue;
        }
        lua_pushlstring(L, filename, 2);
        lua_pushstring(L, type);
        return 2;
      }
      return 0;
    }

    if (dp->h == INVALID_HANDLE_VALUE)
      return 0;
    for (; ; ) {
      int res, is_dots = 1;
      {
        char *path = filename_to_utf8(filename);
        if (!path)
          return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY);

        if (!(path[0] == '.' && (path[1] == '\0'
         || (path[1] == '.' && path[2] == '\0')))) {
          lua_pushstring(L, path);
          lua_pushboolean(L,
           dp->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
          is_dots = 0;
        }

        free(path);
      }

      sys_vm_leave(L);
      res = is_WinNT
       ? FindNextFileW(dp->h, &dp->data)
       : FindNextFileA(dp->h, (WIN32_FIND_DATAA *) &dp->data);
      sys_vm_enter(L);

      if (!res) {
        FindClose(dp->h);
        dp->h = INVALID_HANDLE_VALUE;
        return is_dots ? 0 : 2;
      }
      if (!is_dots) break;
    }
    return 2;
#endif
  }
}
Exemplo n.º 27
0
bool IosBackupAdapter::UnBackup( const std::wstring& appDir, const std::string& password )
{
    std::wstring unBackupTool = Utils::GetExePath() + L"\\tools\\ios_backup\\backup_tool.exe";

    std::wstring originDir = appDir;
    std::wstring unBackupDir = appDir;

    // If already unbackup, just return
    if ( Utils::FileExist(unBackupDir + L"\\Manifest.plist") )
        return true;

    PROCESS_INFORMATION piProcInfo = {0};
    STARTUPINFOA siStartInfo = {0};

    siStartInfo.wShowWindow = SW_HIDE;

    // Find hash dir such as '8c386c653b87f810d28b6e674f2ee2d75a456e02'
    std::wstring hashDir;
    std::wstring findStr = originDir + L"\\*.*";
    WIN32_FIND_DATAW fd = {0};

    HANDLE hf = FindFirstFile(findStr.c_str(), &fd);

    if ( INVALID_HANDLE_VALUE == hf )
        return true;

    do
    {
        if ( wcslen(fd.cFileName) == wcslen(L"8c386c653b87f810d28b6e674f2ee2d75a456e02") )
        {
            hashDir = fd.cFileName;
            break;
        }

    } while ( FindNextFileW(hf, &fd) );

    FindClose(hf);

    if ( hashDir.empty() )
    {
        Utils::__TRACE(L"[IosBackupAdapter] Cannot find hash dir.\r\n");
        return true;
    }

    // Create process 'backup_tool.exe'
    char cmd[1024] = {0};
    wsprintfA(cmd, " \"%s\\%s\" \"%s\" 0 9999 %s",
              Utils::WideToAnsi(originDir).c_str(),
              Utils::WideToAnsi(hashDir).c_str(),
              Utils::WideToAnsi(unBackupDir).c_str(),
              password.c_str());

    if ( !CreateProcessA(Utils::WideToAnsi(unBackupTool).c_str(), cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &siStartInfo, &piProcInfo) )
    {
        Utils::__TRACE(L"[IosBackupAdapter] CreateProcessW failed. [%d] [%s] \r\n", GetLastError(), Utils::AnsiToWide(cmd).c_str());
        return true;
    }

    WaitForSingleObject(piProcInfo.hProcess, INFINITE);

    CloseHandle(piProcInfo.hProcess);
    CloseHandle(piProcInfo.hThread);

    return Utils::FileExist(unBackupDir + L"\\Manifest.plist");
}
Exemplo n.º 28
0
bool MCFileSystemListEntries(const char *p_folder, uint32_t p_options, MCFileSystemListCallback p_callback, void *p_context)
{
	bool t_success;
	t_success = true;

	char *t_pattern;
	t_pattern = nil;
	if (t_success)
		t_success = MCCStringFormat(t_pattern, "%s%s", p_folder, MCCStringEndsWith(p_folder, "/") ? "*" : "/*");

	void *t_native_pattern;
	t_native_pattern = nil;
	if (t_success)
		t_success = MCFileSystemPathToNative(t_pattern, t_native_pattern);

	HANDLE t_find_handle;
	WIN32_FIND_DATAW t_find_data;
	t_find_handle = INVALID_HANDLE_VALUE;
	if (t_success)
	{
		t_find_handle = FindFirstFileW((LPCWSTR)t_native_pattern, &t_find_data);
		if (t_find_handle == INVALID_HANDLE_VALUE)
			t_success = false;
	}

	while(t_success)
	{
		char *t_entry_filename;
		if (t_success)
			t_success = MCFileSystemPathFromNative(t_find_data . cFileName, t_entry_filename);

		MCFileSystemEntry t_entry;
		if (t_success)
		{
			t_entry . type = (t_find_data . dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ? kMCFileSystemEntryFolder : kMCFileSystemEntryFile;
			t_entry . filename = t_entry_filename;

			t_success = p_callback(p_context, t_entry);
		}

		MCCStringFree(t_entry_filename);

		////

		if (!FindNextFileW(t_find_handle, &t_find_data))
		{
			if (GetLastError() == ERROR_NO_MORE_FILES)
				break;

			t_success = false;
		}
	}

	if (t_find_handle != INVALID_HANDLE_VALUE)
		FindClose(t_find_handle);

	MCMemoryDeallocate(t_native_pattern);
	MCCStringFree(t_pattern);

	return t_success;
}
Exemplo n.º 29
0
void unpackJars(LauncherProperties * props, WCHAR * jvmDir, WCHAR * startDir, WCHAR * unpack200exe) {
    DWORD attrs;
    DWORD dwError;
    DWORD count = 0 ;
    
    if(!isOK(props)) return;
    attrs = GetFileAttributesW(startDir);
    if(attrs==INVALID_FILE_ATTRIBUTES) {
        writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t get attributes of the file : ", startDir, GetLastError());
        return;
    }
    if(attrs & FILE_ATTRIBUTE_DIRECTORY) { // is directory
        WIN32_FIND_DATAW FindFileData;
        HANDLE hFind = INVALID_HANDLE_VALUE;
        
        WCHAR * DirSpec = appendStringW(appendStringW(NULL, startDir), L"\\*" );
        
        // Find the first file in the directory.
        hFind = FindFirstFileW(DirSpec, &FindFileData);
        
        if (hFind == INVALID_HANDLE_VALUE) {
            writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t file with pattern ", DirSpec, GetLastError());
        }
        else {
            // List all the other files in the directory.
            writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... listing directory ", 0);
            writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, startDir, 1);
            
            while (FindNextFileW(hFind, &FindFileData) != 0 && isOK(props)) {
                if(lstrcmpW(FindFileData.cFileName, L".")!=0 &&
                        lstrcmpW(FindFileData.cFileName, L"..")!=0) {
                    WCHAR * child = NULL;
                    
                    child = appendStringW(appendStringW(appendStringW(NULL, startDir), FILE_SEP), FindFileData.cFileName);
                    if(isDirectory(child)) {
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... directory : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, child, 1);
                        unpackJars(props, jvmDir, child, unpack200exe);
                    } else  if(searchW(FindFileData.cFileName, JAR_PACK_GZ_SUFFIX)!=NULL) {
                        WCHAR * jarName = appendStringW(appendStringW(
                                appendStringW(NULL, startDir), FILE_SEP),
                                appendStringNW(NULL, 0, FindFileData.cFileName,
                                getLengthW(FindFileData.cFileName) - getLengthW(PACK_GZ_SUFFIX)));
                        WCHAR * unpackCommand = NULL;
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... packed jar : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, child, 1);
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... jar name : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, jarName, 1);
                        
                        
                        appendCommandLineArgument(&unpackCommand, unpack200exe);
                        appendCommandLineArgument(&unpackCommand, child);
                        appendCommandLineArgument(&unpackCommand, jarName);
                        
                        executeCommand(props, unpackCommand, NULL, UNPACK200_EXTRACTION_TIMEOUT, props->stdoutHandle, props->stderrHandle, NORMAL_PRIORITY_CLASS);
                        FREE(unpackCommand);
                        if(!isOK(props)) {
                            if(props->status==ERROR_PROCESS_TIMEOUT) {
                                writeMessageA(props, OUTPUT_LEVEL_DEBUG, 1, "... could not unpack file : timeout", 1);
                            } else {
                                writeMessageA(props, OUTPUT_LEVEL_DEBUG, 1, "... an error occured unpacking the file", 1);
                            }
                            props->exitCode = props->status;
                        }
                        FREE(jarName);
                    }
                    FREE(child);
                }
            }
            
            dwError = GetLastError();
            FindClose(hFind);
            if (dwError != ERROR_NO_MORE_FILES) {
                writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t find file with pattern : ", DirSpec, dwError);
            }
        }
        FREE(DirSpec);
    }
    
}
Exemplo n.º 30
0
void __PHYSFS_platformEnumerateFiles(const char *dirname,
	PHYSFS_EnumFilesCallback callback,
	const char *origdir,
	void *callbackdata)
{

	HANDLE dir = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATAW entw;
	size_t len = strlen(dirname);
	char *searchPath = NULL;
	WCHAR *wSearchPath = NULL;

	/* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
	searchPath = (char *)__PHYSFS_smallAlloc(len + 3);
	if (searchPath == NULL)
		return;

	/* Copy current dirname */
	strcpy(searchPath, dirname);

	/* if there's no '\\' at the end of the path, stick one in there. */
	if (searchPath[len - 1] != '\\')
	{
		searchPath[len++] = '\\';
		searchPath[len] = '\0';
	} /* if */

	/* Append the "*" to the end of the string */
	strcat(searchPath, "*");

	UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
	if (!wSearchPath)
		return;  /* oh well. */

	//dir = FindFirstFileW(wSearchPath, &entw);
	dir = FindFirstFileExW(wSearchPath, FindExInfoStandard, &entw, FindExSearchNameMatch, NULL, 0);

	__PHYSFS_smallFree(wSearchPath);
	__PHYSFS_smallFree(searchPath);
	if (dir == INVALID_HANDLE_VALUE)
		return;

	do
	{
		const DWORD attr = entw.dwFileAttributes;
		const DWORD tag = entw.dwReserved0;
		const WCHAR *fn = entw.cFileName;
		char *utf8;

		if ((fn[0] == '.') && (fn[1] == '\0'))
			continue;
		if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
			continue;

		utf8 = unicodeToUtf8Heap(fn);
		if (utf8 != NULL)
		{
			callback(callbackdata, origdir, utf8);
			allocator.Free(utf8);
		} /* if */
	} while (FindNextFileW(dir, &entw) != 0);

	FindClose(dir);
} /* __PHYSFS_platformEnumerateFiles */