// Detect It Easy: detection rule file

// Author: DosX
// E-Mail: collab@kay-software.ru
// GitHub: https://github.com/DosX-dev
// Telegram: @DosX_dev

meta("debug data", "");

function detect() {
    var size = Binary.getSize();

    // Borland debug info
    if (Binary.readWord(0) === 0x52FB) {
        var minor = Binary.readByte(2),
            major = Binary.readByte(3),
            minorStr = ((minor >> 4) * 10 + (minor & 0x0F)).toString(),
            majorStr = ((major >> 4) * 10 + (major & 0x0F)).toString(),
            sVer = majorStr + "." + minorStr;

        _setResult(sType, "Borland", sVer, "TDS" + (Binary.readWord(0xE) ? " " + Binary.readWord(0xE) + " symbols" : ""));
        return true;
    } else if (Binary.compare("'FB09'")) {
        _setResult(sType, "Borland", "", "Delphi TDS");
        return true;
    } else if (Binary.compare("'FB0A'")) {
        _setResult(sType, "Borland", "", "C++ TDS");
        return true;
    }

    var debugSize = Binary.readDword(size - 4);

    // Watcom debug info
    if (size > 16 && Binary.readWord(size - 14) === 0x8386) {
        if (size - debugSize >= 0) {
            _setResult(sType, "Watcom", Binary.readByte(size - 12) + "." + Binary.readByte(size - 11), "0x" + debugSize.toString(16) + " bytes");
        }
        return true;
    }

    // CodeView debug info
    if (size > 16 && Binary.readWord(size - 8) === 0x424E) {
        if (/^NB0[5789]|NB1[01]$/.test(Binary.read_ansiString(size - 8, 4))) {
            if (size - debugSize >= 0) {
                _setResult(sType, "CodeView", "4.0", "0x" + debugSize.toString(16) + " bytes");
            }
            return true;
        }
    }

    // DWARF debug info
    if (size > 16 && Binary.readDword(size - 16) === 0x534954) {
        if (Binary.readDword(size - 12) === 0 && Binary.readDword(size - 8) === 0) {

            var debugOffset = size - debugSize;

            if (debugOffset >= 0) {
                var viStruct = get_DWRAF_vi(debugOffset, size - debugOffset);
                if (viStruct.bIsValid) {
                    _setResult(sType, "DWARF", viStruct.sVersion, "0x" + debugSize.toString(16) + " bytes, Watcom");
                }
                return true;
            }
        }
    }

    if (Binary.isDebugData()) {
        if (Binary.compare("'RSDS'")) {
            sName = "PDB file link";
            _setResult(sType, sName, "7.0", "");
            return true;
        }
    }

    return result();
}
