.. _debugger-general-list: General Debugger Commands ========================= You can also type **help ** for further details on each command in the MAME Debugger interface. | :ref:`debugger-command-do` -- evaluates the given expression | :ref:`debugger-command-symlist` -- lists registered symbols | :ref:`debugger-command-softreset` -- executes a soft reset | :ref:`debugger-command-hardreset` -- executes a hard reset | :ref:`debugger-command-print` -- prints one or more s to the console | :ref:`debugger-command-printf` -- prints one or more s to the console using | :ref:`debugger-command-logerror` -- outputs one or more s to the error.log | :ref:`debugger-command-tracelog` -- outputs one or more s to the trace file using | :ref:`debugger-command-tracesym` -- outputs one or more s to the trace file | history -- outputs a brief history of visited opcodes (**to fix: help missing for this command**) | :ref:`debugger-command-trackpc` -- visually track visited opcodes [boolean to turn on and off, for the given CPU, clear] | :ref:`debugger-command-trackmem` -- record which PC writes to each memory address [boolean to turn on and off, clear] | :ref:`debugger-command-pcatmem` -- query which PC wrote to a given memory address for the current CPU | :ref:`debugger-command-rewind` -- go back in time by loading the most recent rewind state | :ref:`debugger-command-statesave` -- save a state file for the current driver | :ref:`debugger-command-stateload` -- load a state file for the current driver | :ref:`debugger-command-snap` -- save a screen snapshot. | :ref:`debugger-command-source` -- reads commands from and executes them one by one | :ref:`debugger-command-quit` -- exits MAME and the debugger .. _debugger-command-do: do -- | **do ** | | The do command simply evaluates the given . This is typically used to set or modify variables. | | Examples: | | do pc = 0 | | Sets the register 'pc' to 0. | | Back to :ref:`debugger-general-list` .. _debugger-command-symlist: symlist ------- | **symlist []** | | Lists registered symbols. If is not specified, then symbols in the global symbol table are displayed; otherwise, the symbols for 's specific CPU are displayed. Symbols are listed alphabetically. Read-only symbols are flagged with an asterisk. | | Examples: | | symlist | | Displays the global symbol table. | | symlist 2 | | Displays the symbols specific to CPU #2. | | Back to :ref:`debugger-general-list` .. _debugger-command-softreset: softreset --------- | **softreset** | | Executes a soft reset. | | Examples: | | softreset | | Executes a soft reset. | | Back to :ref:`debugger-general-list` .. _debugger-command-hardreset: hardreset --------- | **hardreset** | | Executes a hard reset. | | Examples: | | hardreset | | Executes a hard reset. | | Back to :ref:`debugger-general-list` .. _debugger-command-print: print ----- | **print [,...]** | | The print command prints the results of one or more expressions to the debugger console as hexadecimal values. | | Examples: | | print pc | | Prints the value of 'pc' to the console as a hex number. | | print a,b,a+b | | Prints a, b, and the value of a+b to the console as hex numbers. | | Back to :ref:`debugger-general-list` .. _debugger-command-printf: printf ------ | **printf [,[,...]]** | | The printf command performs a C-style printf to the debugger console. Only a very limited set of formatting options are available: | | %[0][]d -- prints as a decimal value with optional digit count and zero-fill | %[0][]x -- prints as a hexadecimal value with optional digit count and zero-fill | | All remaining formatting options are ignored. Use %% together to output a % character. Multiple lines can be printed by embedding a \\n in the text. | | Examples: | | printf "PC=%04X",pc | | Prints PC= where is displayed in hexadecimal with 4 digits with zero-fill. | | printf "A=%d, B=%d\\nC=%d",a,b,a+b | | Prints A=, B= on one line, and C= on a second line. | | Back to :ref:`debugger-general-list` .. _debugger-command-logerror: logerror -------- | **logerror [,[,...]]** | | The logerror command performs a C-style printf to the error log. Only a very limited set of formatting options are available: | | %[0][]d -- logs as a decimal value with optional digit count and zero-fill | %[0][]x -- logs as a hexadecimal value with optional digit count and zero-fill | | All remaining formatting options are ignored. Use %% together to output a % character. Multiple lines can be printed by embedding a \\n in the text. | | Examples: | | logerror "PC=%04X",pc | | Logs PC= where is displayed in hexadecimal with 4 digits with zero-fill. | | logerror "A=%d, B=%d\\nC=%d",a,b,a+b | | Logs A=, B= on one line, and C= on a second line. | | Back to :ref:`debugger-general-list` .. _debugger-command-tracelog: tracelog -------- | **tracelog [,[,...]]** | | The tracelog command performs a C-style printf and routes the output to the currently open trace file (see the 'trace' command for details). If no file is currently open, tracelog does nothing. Only a very limited set of formatting options are available. See the :ref:`debugger-command-printf` help for details. | | Examples: | | tracelog "PC=%04X",pc | | Outputs PC= where is displayed in hexadecimal with 4 digits with zero-fill. | | printf "A=%d, B=%d\\nC=%d",a,b,a+b | | Outputs A=, B= on one line, and C= on a second line. | | Back to :ref:`debugger-general-list` .. _debugger-command-tracesym: tracesym -------- | **tracesym [,...]** | | The tracesym command prints the specified symbols and routes the output to the currently open trace file (see the 'trace' command for details). If no file is currently open, tracesym does nothing. | | Examples: | | tracelog pc | | Outputs PC= where is displayed in the default format. | | Back to :ref:`debugger-general-list` .. _debugger-command-trackpc: trackpc ------- | **trackpc [,,]** | | The trackpc command displays which program counters have already been visited in all disassembler windows. The first boolean argument toggles the process on and off. The second argument is a CPU selector; if no CPU is specified, the current CPU is automatically selected. The third argument is a boolean denoting if the existing data should be cleared or not. | | Examples: | | trackpc 1 | | Begin tracking the current CPU's pc. | | trackpc 1, 0, 1 | | Continue tracking pc on CPU 0, but clear existing track info. | | Back to :ref:`debugger-general-list` .. _debugger-command-trackmem: trackmem -------- | **trackmem [,,]** | | The trackmem command logs the PC at each time a memory address is written to. The first boolean argument toggles the process on and off. The second argument is a CPU selector; if no CPU is specified, the current CPU is automatically selected. The third argument is a boolean denoting if the existing data should be cleared or not. Please refer to the pcatmem command for information on how to retrieve this data. Also, right clicking in a memory window will display the logged PC for the given address. | | Examples: | | trackmem | | Begin tracking the current CPU's pc. | | trackmem 1, 0, 1 | | Continue tracking memory writes on CPU 0, but clear existing track info. | | Back to :ref:`debugger-general-list` .. _debugger-command-pcatmem: pcatmem ------- | **pcatmem(p/d/i)
[,]** | | **pcatmemp
[,]** -- query which PC wrote to a given program memory address for the current CPU | **pcatmemd
[,]** -- query which PC wrote to a given data memory address for the current CPU | **pcatmemi
[,]** -- query which PC wrote to a given I/O memory address for the current CPU (you can also query this info by right clicking in a memory window) | | The pcatmem command returns which PC wrote to a given memory address for the current CPU. The first argument is the requested address. The second argument is a CPU selector; if no CPU is specified, the current CPU is automatically selected. Right clicking in a memory window will also display the logged PC for the given address. | | Examples: | | pcatmem 400000 | | Print which PC wrote this CPU's memory location 0x400000. | | Back to :ref:`debugger-general-list` .. _debugger-command-rewind: rewind ------ | **rewind[rw]** | | The rewind command loads the most recent RAM-based state. Rewind states, when enabled, are saved when "step", "over", or "out" command gets executed, storing the machine state as of the moment before actually stepping. Consecutively loading rewind states can work like reverse execution. Depending on which steps forward were taken previously, the behavior can be similar to GDB's "reverse-stepi" or "reverse-next". All output for this command is currently echoed into the running machine window. Previous memory and PC tracking statistics are cleared, actual reverse execution does not occur. | | Back to :ref:`debugger-general-list` .. _debugger-command-statesave: statesave --------- | **statesave[ss] ** | | The statesave command creates a save state at this exact moment in time. The given state file gets written to the standard state directory (sta), and gets .sta added to it - no file extension necessary. All output for this command is currently echoed into the running machine window. | | Examples: | | statesave foo | | Writes file 'foo.sta' in the default state save directory. | | Back to :ref:`debugger-general-list` .. _debugger-command-stateload: stateload --------- | **stateload[sl] ** | | The stateload command retrieves a save state from disk. The given state file gets read from the standard state directory (sta), and gets .sta added to it - no file extension necessary. All output for this command is currently echoed into the running machine window. Previous memory and PC tracking statistics are cleared. | | Examples: | | stateload foo | | Reads file 'foo.sta' from the default state save directory. | | Back to :ref:`debugger-general-list` .. _debugger-command-snap: snap ---- | **snap [[], ]** | | The snap command takes a snapshot of the current video display and saves it to the configured snapshot directory. If is specified explicitly, a single screenshot for is saved under the requested filename. If is omitted, all screens are saved using the same default rules as the "save snapshot" key in MAME proper. | | Examples: | | snap | | Takes a snapshot of the current video screen and saves to the next non-conflicting filename in the configured snapshot directory. | | snap shinobi | | Takes a snapshot of the current video screen and saves it as 'shinobi.png' in the configured snapshot directory. | | Back to :ref:`debugger-general-list` .. _debugger-command-source: source ------ | **source ** | | The source command reads in a set of debugger commands from a file and executes them one by one, similar to a batch file. | | Examples: | | source break_and_trace.cmd | | Reads in debugger commands from break_and_trace.cmd and executes them. | | Back to :ref:`debugger-general-list` .. _debugger-command-quit: quit ---- | **quit** | | The quit command exits MAME immediately. | | Back to :ref:`debugger-general-list` 88 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
// PropIDUtils.cpp

#include "StdAfx.h"

#include "../../../../C/CpuArch.h"

#include "../../../Common/IntToString.h"
#include "../../../Common/StringConvert.h"

#include "../../../Windows/FileIO.h"
#include "../../../Windows/PropVariantConv.h"

#include "../../PropID.h"

#include "PropIDUtils.h"

#define Get16(x) GetUi16(x)
#define Get32(x) GetUi32(x)

using namespace NWindows;

static const char g_WinAttribChars[16 + 1] = "RHS8DAdNTsLCOnE_";
/*
0 READONLY
1 HIDDEN
2 SYSTEM

4 DIRECTORY
5 ARCHIVE
6 DEVICE
7 NORMAL
8 TEMPORARY
9 SPARSE_FILE
10 REPARSE_POINT
11 COMPRESSED
12 OFFLINE
13 NOT_CONTENT_INDEXED
14 ENCRYPTED

16 VIRTUAL
*/

static const char kPosixTypes[16] = { '0', 'p', 'c', '3', 'd', '5', 'b', '7', '-', '9', 'l', 'B', 's', 'D', 'E', 'F' };
#define MY_ATTR_CHAR(a, n, c) ((a) & (1 << (n))) ? c : '-';

static void ConvertPosixAttribToString(char *s, UInt32 a) throw()
{
  s[0] = kPosixTypes[(a >> 12) & 0xF];
  for (int i = 6; i >= 0; i -= 3)
  {
    s[7 - i] = MY_ATTR_CHAR(a, i + 2, 'r');
    s[8 - i] = MY_ATTR_CHAR(a, i + 1, 'w');
    s[9 - i] = MY_ATTR_CHAR(a, i + 0, 'x');
  }
  if ((a & 0x800) != 0) s[3] = ((a & (1 << 6)) ? 's' : 'S');
  if ((a & 0x400) != 0) s[6] = ((a & (1 << 3)) ? 's' : 'S');
  if ((a & 0x200) != 0) s[9] = ((a & (1 << 0)) ? 't' : 'T');
  s[10] = 0;
  
  a &= ~(UInt32)0xFFFF;
  if (a != 0)
  {
    s[10] = ' ';
    ConvertUInt32ToHex8Digits(a, s + 11);
  }
}

void ConvertWinAttribToString(char *s, UInt32 wa) throw()
{
  for (int i = 0; i < 16; i++)
    if ((wa & (1 << i)) && i != 7)
      *s++ = g_WinAttribChars[i];
  *s = 0;

  // we support p7zip trick that stores posix attributes in high 16 bits, and 0x8000 flag
  // we also support ZIP archives created in Unix, that store posix attributes in high 16 bits without 0x8000 flag
  
  // if (wa & 0x8000)
  if ((wa >> 16) != 0)
  {
    *s++ = ' ';
    ConvertPosixAttribToString(s, wa >> 16);
  }
}

void ConvertPropertyToShortString(char *dest, const PROPVARIANT &prop, PROPID propID, bool full) throw()
{
  *dest = 0;
  
  if (prop.vt == VT_FILETIME)
  {
    FILETIME localFileTime;
    if ((prop.filetime.dwHighDateTime == 0 &&
        prop.filetime.dwLowDateTime == 0) ||
        !::FileTimeToLocalFileTime(&prop.filetime, &localFileTime))
      return;
    ConvertFileTimeToString(localFileTime, dest, true, full);
    return;
  }

  switch (propID)
  {
    case kpidCRC:
    {
      if (prop.vt != VT_UI4)
        break;
      ConvertUInt32ToHex8Digits(prop.ulVal, dest);
      return;
    }
    case kpidAttrib:
    {
      if (prop.vt != VT_UI4)
        break;
      UInt32 a = prop.ulVal;

      /*
      if ((a & 0x8000) && (a & 0x7FFF) == 0)
        ConvertPosixAttribToString(dest, a >> 16);
      else
      */
      ConvertWinAttribToString(dest, a);
      return;
    }
    case kpidPosixAttrib:
    {
      if (prop.vt != VT_UI4)
        break;
      ConvertPosixAttribToString(dest, prop.ulVal);
      return;
    }
    case kpidINode:
    {
      if (prop.vt != VT_UI8)
        break;
      ConvertUInt32ToString((UInt32)(prop.uhVal.QuadPart >> 48), dest);
      dest += strlen(dest);
      *dest++ = '-';
      UInt64 low = prop.uhVal.QuadPart & (((UInt64)1 << 48) - 1);
      ConvertUInt64ToString(low, dest);
      return;
    }
    case kpidVa:
    {
      UInt64 v = 0;
      if (prop.vt == VT_UI4)
        v = prop.ulVal;
      else if (prop.vt == VT_UI8)
        v = (UInt64)prop.uhVal.QuadPart;
      else
        break;
      dest[0] = '0';
      dest[1] = 'x';
      ConvertUInt64ToHex(v, dest + 2);
      return;
    }
  }
  
  ConvertPropVariantToShortString(prop, dest);
}

void ConvertPropertyToString(UString &dest, const PROPVARIANT &prop, PROPID propID, bool full)
{
  if (prop.vt == VT_BSTR)
  {
    dest.SetFromBstr(prop.bstrVal);
    return;
  }
  char temp[64];
  ConvertPropertyToShortString(temp, prop, propID, full);
  dest.SetFromAscii(temp);
}

static inline unsigned GetHex(unsigned v)
{
  return (v < 10) ? ('0' + v) : ('A' + (v - 10));
}

#ifndef _SFX

static inline void AddHexToString(AString &res, unsigned v)
{
  res += (char)GetHex(v >> 4);
  res += (char)GetHex(v & 0xF);
  res += ' ';
}

/*
static AString Data_To_Hex(const Byte *data, size_t size)
{
  AString s;
  for (size_t i = 0; i < size; i++)
    AddHexToString(s, data[i]);
  return s;
}
*/

static const char * const sidNames[] =
{
    "0"
  , "Dialup"
  , "Network"
  , "Batch"
  , "Interactive"
  , "Logon"  // S-1-5-5-X-Y
  , "Service"
  , "Anonymous"
  , "Proxy"
  , "EnterpriseDC"
  , "Self"
  , "AuthenticatedUsers"
  , "RestrictedCode"
  , "TerminalServer"
  , "RemoteInteractiveLogon"
  , "ThisOrganization"
  , "16"
  , "IUserIIS"
  , "LocalSystem"
  , "LocalService"
  , "NetworkService"
  , "Domains"
};

struct CSecID2Name
{
  UInt32 n;
  const char *sz;
};

static const CSecID2Name sid_32_Names[] =
{
  { 544, "Administrators" },
  { 545, "Users" },
  { 546, "Guests" },
  { 547, "PowerUsers" },
  { 548, "AccountOperators" },
  { 549, "ServerOperators" },
  { 550, "PrintOperators" },
  { 551, "BackupOperators" },
  { 552, "Replicators" },
  { 553, "Backup Operators" },
  { 554, "PreWindows2000CompatibleAccess" },
  { 555, "RemoteDesktopUsers" },
  { 556, "NetworkConfigurationOperators" },
  { 557, "IncomingForestTrustBuilders" },
  { 558, "PerformanceMonitorUsers" },
  { 559, "PerformanceLogUsers" },
  { 560, "WindowsAuthorizationAccessGroup" },
  { 561, "TerminalServerLicenseServers" },
  { 562, "DistributedCOMUsers" },
  { 569, "CryptographicOperators" },
  { 573, "EventLogReaders" },
  { 574, "CertificateServiceDCOMAccess" }
};

static const CSecID2Name sid_21_Names[] =
{
  { 500, "Administrator" },
  { 501, "Guest" },
  { 502, "KRBTGT" },
  { 512, "DomainAdmins" },
  { 513, "DomainUsers" },
  { 515, "DomainComputers" },
  { 516, "DomainControllers" },
  { 517, "CertPublishers" },
  { 518, "SchemaAdmins" },
  { 519, "EnterpriseAdmins" },
  { 520, "GroupPolicyCreatorOwners" },
  { 553, "RASandIASServers" },
  { 553, "RASandIASServers" },
  { 571, "AllowedRODCPasswordReplicationGroup" },
  { 572, "DeniedRODCPasswordReplicationGroup" }
};

struct CServicesToName
{
  UInt32 n[5];
  const char *sz;
};

static const CServicesToName services_to_name[] =
{
  { { 0x38FB89B5, 0xCBC28419, 0x6D236C5C, 0x6E770057, 0x876402C0 } , "TrustedInstaller" }
};

static void ParseSid(AString &s, const Byte *p, UInt32 lim, UInt32 &sidSize)
{
  sidSize = 0;
  if (lim < 8)
  {
    s += "ERROR";
    return;
  }
  UInt32 rev = p[0];
  if (rev != 1)
  {
    s += "UNSUPPORTED";
    return;
  }
  UInt32 num = p[1];
  if (8 + num * 4 > lim)
  {
    s += "ERROR";
    return;
  }
  sidSize = 8 + num * 4;
  UInt32 authority = GetBe32(p + 4);

  if (p[2] == 0 && p[3] == 0 && authority == 5 && num >= 1)
  {
    UInt32 v0 = Get32(p + 8);
    if (v0 < ARRAY_SIZE(sidNames))
    {
      s += sidNames[v0];
      return;
    }
    if (v0 == 32 && num == 2)
    {
      UInt32 v1 = Get32(p + 12);
      for (unsigned i = 0; i < ARRAY_SIZE(sid_32_Names); i++)
        if (sid_32_Names[i].n == v1)
        {
          s += sid_32_Names[i].sz;
          return;
        }
    }
    if (v0 == 21 && num == 5)
    {
      UInt32 v4 = Get32(p + 8 + 4 * 4);
      for (unsigned i = 0; i < ARRAY_SIZE(sid_21_Names); i++)
        if (sid_21_Names[i].n == v4)
        {
          s += sid_21_Names[i].sz;
          return;
        }
    }
    if (v0 == 80 && num == 6)
    {
      for (unsigned i = 0; i < ARRAY_SIZE(services_to_name); i++)
      {
        const CServicesToName &sn = services_to_name[i];
        int j;
        for (j = 0; j < 5 && sn.n[j] == Get32(p + 8 + 4 + j * 4); j++);
        if (j == 5)
        {
          s += sn.sz;
          return;
        }
      }
    }
  }
  
  char sz[16];
  s += "S-1-";
  if (p[2] == 0 && p[3] == 0)
  {
    ConvertUInt32ToString(authority, sz);
    s += sz;
  }
  else
  {
    s += "0x";
    for (int i = 2; i < 8; i++)
      AddHexToString(s, p[i]);
  }
  for (UInt32 i = 0; i < num; i++)
  {
    s += '-';
    ConvertUInt32ToString(Get32(p + 8 + i * 4), sz);
    s += sz;
  }
}

static void ParseOwner(AString &s, const Byte *p, UInt32 size, UInt32 pos)
{
  if (pos > size)
  {
    s += "ERROR";
    return;
  }
  UInt32 sidSize = 0;
  ParseSid(s, p + pos, size - pos, sidSize);
}

static void AddUInt32ToString(AString &s, UInt32 val)
{
  char sz[16];
  ConvertUInt32ToString(val, sz);
  s += sz;
}

static void ParseAcl(AString &s, const Byte *p, UInt32 size, const char *strName, UInt32 flags, UInt32 offset)
{
  UInt32 control = Get16(p + 2);
  if ((flags & control) == 0)
    return;
  UInt32 pos = Get32(p + offset);
  s += ' ';
  s += strName;
  if (pos >= size)
    return;
  p += pos;
  size -= pos;
  if (size < 8)
    return;
  if (Get16(p) != 2) // revision
    return;
  UInt32 num = Get32(p + 4);
  AddUInt32ToString(s, num);
  
  /*
  UInt32 aclSize = Get16(p + 2);
  if (num >= (1 << 16))
    return;
  if (aclSize > size)
    return;
  size = aclSize;
  size -= 8;
  p += 8;
  for (UInt32 i = 0 ; i < num; i++)
  {
    if (size <= 8)
      return;
    // Byte type = p[0];
    // Byte flags = p[1];
    // UInt32 aceSize = Get16(p + 2);
    // UInt32 mask = Get32(p + 4);
    p += 8;
    size -= 8;

    UInt32 sidSize = 0;
    s += ' ';
    ParseSid(s, p, size, sidSize);
    if (sidSize == 0)
      return;
    p += sidSize;
    size -= sidSize;
  }

  // the tail can contain zeros. So (size != 0) is not ERROR
  // if (size != 0) s += " ERROR";
  */
}

#define MY_SE_OWNER_DEFAULTED       (0x0001)
#define MY_SE_GROUP_DEFAULTED       (0x0002)
#define MY_SE_DACL_PRESENT          (0x0004)
#define MY_SE_DACL_DEFAULTED        (0x0008)
#define MY_SE_SACL_PRESENT          (0x0010)
#define MY_SE_SACL_DEFAULTED        (0x0020)
#define MY_SE_DACL_AUTO_INHERIT_REQ (0x0100)
#define MY_SE_SACL_AUTO_INHERIT_REQ (0x0200)
#define MY_SE_DACL_AUTO_INHERITED   (0x0400)
#define MY_SE_SACL_AUTO_INHERITED   (0x0800)
#define MY_SE_DACL_PROTECTED        (0x1000)
#define MY_SE_SACL_PROTECTED        (0x2000)
#define MY_SE_RM_CONTROL_VALID      (0x4000)
#define MY_SE_SELF_RELATIVE         (0x8000)

void ConvertNtSecureToString(const Byte *data, UInt32 size, AString &s)
{
  s.Empty();
  if (size < 20 || size > (1 << 18))
  {
    s += "ERROR";
    return;
  }
  if (Get16(data) != 1) // revision
  {
    s += "UNSUPPORTED";
    return;
  }
  ParseOwner(s, data, size, Get32(data + 4));
  s += ' ';
  ParseOwner(s, data, size, Get32(data + 8));
  ParseAcl(s, data, size, "s:", MY_SE_SACL_PRESENT, 12);
  ParseAcl(s, data, size, "d:", MY_SE_DACL_PRESENT, 16);
  s += ' ';
  AddUInt32ToString(s, size);
  // s += '\n';
  // s += Data_To_Hex(data, size);
}

#ifdef _WIN32

static bool CheckSid(const Byte *data, UInt32 size, UInt32 pos) throw()
{
  if (pos >= size)
    return false;
  size -= pos;
  if (size < 8)
    return false;
  UInt32 rev = data[pos];
  if (rev != 1)
    return false;
  UInt32 num = data[pos + 1];
  return (8 + num * 4 <= size);
}

static bool CheckAcl(const Byte *p, UInt32 size, UInt32 flags, UInt32 offset) throw()
{
  UInt32 control = Get16(p + 2);
  if ((flags & control) == 0)
    return true;
  UInt32 pos = Get32(p + offset);
  if (pos >= size)
    return false;
  p += pos;
  size -= pos;
  if (size < 8)
    return false;
  UInt32 aclSize = Get16(p + 2);
  return (aclSize <= size);
}

bool CheckNtSecure(const Byte *data, UInt32 size) throw()
{
  if (size < 20)
    return false;
  if (Get16(data) != 1) // revision
    return true; // windows function can handle such error, so we allow it
  if (size > (1 << 18))
    return false;
  if (!CheckSid(data, size, Get32(data + 4))) return false;
  if (!CheckSid(data, size, Get32(data + 8))) return false;
  if (!CheckAcl(data, size, MY_SE_SACL_PRESENT, 12)) return false;
  if (!CheckAcl(data, size, MY_SE_DACL_PRESENT, 16)) return false;
  return true;
}

#endif

bool ConvertNtReparseToString(const Byte *data, UInt32 size, UString &s)
{
  s.Empty();
  NFile::CReparseAttr attr;
  if (attr.Parse(data, size))
  {
    if (!attr.IsSymLink())
      s.AddAscii("Junction: ");
    s += attr.GetPath();
    if (!attr.IsOkNamePair())
    {
      s.AddAscii(" : ");
      s += attr.PrintName;
    }
    return true;
  }

  if (size < 8)
    return false;
  UInt32 tag = Get32(data);
  UInt32 len = Get16(data + 4);
  if (len + 8 > size)
    return false;
  if (Get16(data + 6) != 0) // padding
    return false;

  char hex[16];
  ConvertUInt32ToHex8Digits(tag, hex);
  s.AddAscii(hex);
  s.Add_Space();

  data += 8;

  for (UInt32 i = 0; i < len; i++)
  {
    unsigned b = ((const Byte *)data)[i];
    s += (wchar_t)GetHex((b >> 4) & 0xF);
    s += (wchar_t)GetHex(b & 0xF);
  }
  return true;
}

#endif