/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of SourcePawn.
 *
 * SourcePawn is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * SourcePawn is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * SourcePawn. If not, see http://www.gnu.org/licenses/.
 */

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#include <sys/stat.h>
#include "Platform.h"

using namespace ke;

static inline DWORD
ToProtBits(OS::Protection prot)
{
    switch (prot) {
      case OS::Prot_ReadWrite:
        return PAGE_READWRITE;
      case OS::Prot_ReadWriteExecute:
        return PAGE_EXECUTE_READWRITE;
      default:
        assert(prot == OS::Prot_ReadExecute);
        return PAGE_EXECUTE_READ;
    }
}

Address
OS::MapMemory(size_t amount, MapMode mode, Protection prot_)
{
    DWORD prot = ToProtBits(prot_);
    DWORD type = MEM_RESERVE;
    if (mode == Map_Commit)
        type |= MEM_COMMIT;

    return (Address)VirtualAlloc(NULL, amount, type, prot);
}

bool
OS::CommitMemory(Address address, size_t amount, Protection prot_)
{
    DWORD prot = ToProtBits(prot_);
    return !!VirtualAlloc(address, amount, MEM_COMMIT, prot);
}

void
OS::UnmapMemory(Address address, size_t size)
{
    VirtualFree(address, 0, MEM_RELEASE);
}

static Address
MapMemoryAt(Address address, size_t amount, OS::MapMode mode, OS::Protection prot_)
{
    DWORD bits = ToProtBits(prot_);
    DWORD flags = MEM_RESERVE;
    if (mode == OS::Map_Commit)
        flags |= MEM_COMMIT;

    return (Address)VirtualAlloc((LPVOID)address, amount, flags, bits);
}

OS::AlignableMapping
OS::MapAlignedMemory(size_t amount, size_t alignment, MapMode mode)
{
    Address addr = MapMemory(amount, mode, OS::Prot_ReadWrite);
    if (!addr)
        return AlignableMapping(NULL, alignment, 0);

    if (!IsAligned(addr, alignment)) {
        UnmapMemory(addr, amount);

        // Try to grab the next available aligned address.
        addr = AlignedBase(addr, alignment);
        addr = MapMemoryAt(addr + alignment, amount, mode, OS::Prot_ReadWrite);
        while (!addr) {
            // Try to over-allocate to get the right region. This can race
            // with other threads; we expect this to be rare. If this turns
            // out to be a problem, the API is set up such that we can just
            // return two pointers: the base, and the aligned address into
            // the over-allocated region.
            addr = MapMemory(amount + alignment, mode, OS::Prot_ReadWrite);
            if (!addr)
                return AlignableMapping(NULL, alignment, 0);
            UnmapMemory(addr, amount + alignment);
            addr = AlignedBase(addr, alignment);
            addr = MapMemoryAt(addr + alignment, amount, mode, OS::Prot_ReadWrite);
        }
    }

    return AlignableMapping(addr, alignment, amount);
}

void
OS::UnmapAlignedMemory(Address address, size_t size)
{
    OS::UnmapMemory(address, size);
}

bool
OS::GetAbsolutePath(const char *path, AutoFree<char> &chars)
{
    char try1[MAX_PATH];
    DWORD result = GetFullPathName(path, sizeof(try1), try1, NULL);
    if (result <= 0)
        return false;

    // +1 because if result < MAX_PATH, it doesn't include the null terminator.
    chars = (char *)calloc(result + 1, sizeof(char));
    if (!*chars)
        return false;

    if (result <= MAX_PATH) {
        strcpy(*chars, try1);
        return true;
    }

    // We should get the same output on the next try.
    return GetFullPathName(path, result, *chars, NULL) == result - 1;
}

bool
OS::SplitPath(const char *path, AutoFree<char> &base, AutoFree<char> &name)
{
    size_t len = strlen(path);

    // Skip trailing slashes.
    while (len > 1 && (path[len - 1] == '/' || path[len - 1] == '\\'))
        len--;

    for (size_t i = len - 1; i < len; i--) {
        if (path[i] == '\\' || path[i] == '/') {
            name = (char *)calloc(len - i, sizeof(char));
            if (!*name)
                return false;

            strcpy(*name, &path[i + 1]);

            base = (char *)calloc(i + 1, sizeof(char));
            if (!*base)
                return false;

            memcpy(*base, path, i);
            (*base)[i] = '\0';
            return true;
        }
    }
    
    // The path should have been absolute, which contains at least one separator.
    return false;
}

const char *
OS::PathSeparator()
{
    return "\\";
}

OS::PathType
OS::InspectPath(const char *path)
{
    struct _stat s;
    int result = _stat(path, &s);
    if (result != 0)
        return OS::Path_Invalid;

    if (s.st_mode & _S_IFDIR)
        return OS::Path_Folder;
    if (s.st_mode & _S_IFREG)
        return OS::Path_File;

    return OS::Path_Invalid;
}
