public static Int32 FromErrno(Errno value)
 {
     Int32 rval;
     if (FromErrno (value, out rval) == -1)
         ThrowArgumentException (value);
     return rval;
 }
예제 #2
0
	// Handle errors reported by the runtime engine.
	private static void HandleErrorsDir(Errno error)
			{
				switch(error)
				{
					case Errno.Success: break;

					case Errno.ENOENT:
					case Errno.ENOTDIR:
					{
						throw new DirectoryNotFoundException
							(_("IO_DirNotFound"));
					}
					// Not reached.

					case Errno.EACCES:
					{
						throw new UnauthorizedAccessException
							(_("IO_AccessDenied"));
					}
					
					case Errno.ENAMETOOLONG:
					{
						throw new PathTooLongException
							(_("Exception_PathTooLong"));
					}
					
					default:
					{
						throw new IOException(error);
					}
					// Not reached.
				}
			}
	protected SocketException(SerializationInfo info, StreamingContext context)
		: base(info, context)
		{
			errno = Errno.EREMOTEIO;
		}
예제 #4
0
		private static extern int FromErrno (Errno value, out Int32 rval);
예제 #5
0
	internal IOException(Errno errno, String msg, Exception inner)
		: base(msg, inner)
		{
			this.errno = errno;
		}
예제 #6
0
	public IOException(String msg, Exception inner)
		: base(msg, inner)
		{
			errno = Errno.EIO;
		}
		private static int FromErrno (Errno value, out Int32 rval)
		{
			throw new System.NotImplementedException();
		}
예제 #8
0
 public static bool TryToErrno(Int32 value, out Errno rval)
 {
     return(ToErrno(value, out rval) == 0);
 }
예제 #9
0
        public Errno ListXAttr(string path, out List <string> xattrs)
        {
            xattrs = null;

            if (!_mounted)
            {
                return(Errno.AccessDenied);
            }

            Errno err = GetFileEntry(path, out DecodedDirectoryEntry entry);

            if (err != Errno.NoError)
            {
                return(err);
            }

            xattrs = new List <string>();

            if (entry.XattrLength > 0)
            {
                xattrs.Add("org.iso.9660.ea");
            }

            if (entry.AssociatedFile != null)
            {
                xattrs.Add("org.iso.9660.AssociatedFile");
            }

            //if(entry.AppleDosType != null)
            //    xattrs.Add("com.apple.dos.type");

            //if(entry.AppleProDosType != null)
            //    xattrs.Add("com.apple.prodos.type");

            if (entry.ResourceFork != null)
            {
                xattrs.Add("com.apple.ResourceFork");
            }

            //if(entry.FinderInfo != null)
            //    xattrs.Add("com.apple.FinderInfo");

            //if(entry.AppleIcon != null)
            //    xattrs.Add("com.apple.Macintosh.Icon");

            //if(entry.AmigaComment != null)
            //    xattrs.Add("com.amiga.comments");

            if (entry.Flags.HasFlag(FileFlags.Directory) ||
                entry.Extents == null ||
                entry.Extents.Count == 0)
            {
                return(Errno.NoError);
            }

            // TODO: No more exceptions
            try
            {
                byte[] sector = _image.ReadSectorLong((entry.Extents[0].extent * _blockSize) / 2048);

                if (sector[15] != 2)
                {
                    return(Errno.NoError);
                }
            }
            catch
            {
                return(Errno.NoError);
            }

            xattrs.Add("org.iso.mode2.subheader");
            xattrs.Add("org.iso.mode2.subheader.copy");

            return(Errno.NoError);
        }
예제 #10
0
 /// <summary>
 /// Throw an exception for the errno.
 /// </summary>
 /// <param name="errno">The errno to throw an exception for.</param>
 /// <param name="logNoError">If there is no error, log that this was called (meaning a failure occured) but that no error existed.</param>
 public static void ThrowExceptionForErrno(Errno errno, bool logNoError = true)
 {
     var err = GetExceptionForErrno(errno, true);
     if (err == null)
     {
         if (logNoError)
         {
             //TODO: should log that no exception occured
         }
         return;
     }
     throw err;
 }
예제 #11
0
 public PosixException(Errno error)
     : base(error.Describe())
 {
     m_error = error;
 }
	// Internal constructors that are used to set correct error codes.
	internal SocketException(Errno errno)
#if !ECMA_COMPAT
		: base((int)errno, DefaultMessage(null, errno))
#else
		: base(DefaultMessage(null, errno))
	internal SocketException(String msg, Exception inner)
		: base(msg, inner)
		{
			errno = Errno.EREMOTEIO;
		}
	internal SocketException(String msg)
		: base(msg)
		{
			errno = Errno.EREMOTEIO;
		}
예제 #15
0
        public Errno Read(string path, long offset, long size, ref byte[] buf)
        {
            if (size == 0)
            {
                buf = new byte[0];
                return(Errno.NoError);
            }

            if (offset < 0)
            {
                return(Errno.InvalidArgument);
            }

            Errno error = LookupFileId(path, out short fileId, out _);

            if (error != Errno.NoError)
            {
                return(error);
            }

            byte[] tmp;
            if (debug)
            {
                switch (fileId)
                {
                case FILEID_BOOT_SIGNED:
                case FILEID_LOADER_SIGNED:
                case (short)FILEID_MDDF:
                case (short)FILEID_BITMAP:
                case (short)FILEID_SRECORD:
                case (short)FILEID_CATALOG:
                    error = ReadSystemFile(fileId, out tmp);
                    break;

                default:
                    error = ReadFile(fileId, out tmp);
                    break;
                }
            }
            else
            {
                error = ReadFile(fileId, out tmp);
            }

            if (error != Errno.NoError)
            {
                return(error);
            }

            if (offset >= tmp.Length)
            {
                return(Errno.EINVAL);
            }

            if (size + offset >= tmp.Length)
            {
                size = tmp.Length - offset;
            }

            buf = new byte[size];
            Array.Copy(tmp, offset, buf, 0, size);
            return(Errno.NoError);
        }
예제 #16
0
        public Errno Stat(string path, out FileEntryInfo stat)
        {
            stat = null;
            if (!mounted)
            {
                return(Errno.AccessDenied);
            }

            string[] pathElements = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (pathElements.Length != 1)
            {
                return(Errno.NotSupported);
            }

            if (debug)
            {
                if (string.Compare(path, "$", StringComparison.InvariantCulture) == 0 ||
                    string.Compare(path, "$Boot", StringComparison.InvariantCulture) == 0 ||
                    string.Compare(path, "$Bitmap", StringComparison.InvariantCulture) == 0 ||
                    string.Compare(path, "$MDB", StringComparison.InvariantCulture) == 0)
                {
                    stat = new FileEntryInfo
                    {
                        BlockSize  = device.Info.SectorSize,
                        DeviceNo   = 0,
                        GID        = 0,
                        Inode      = 0,
                        Links      = 1,
                        Mode       = 0x124,
                        UID        = 0,
                        Attributes = FileAttributes.System
                    };

                    if (string.Compare(path, "$", StringComparison.InvariantCulture) == 0)
                    {
                        stat.Blocks = directoryBlocks.Length / stat.BlockSize + directoryBlocks.Length % stat.BlockSize;
                        stat.Length = directoryBlocks.Length;
                    }
                    else if (string.Compare(path, "$Bitmap", StringComparison.InvariantCulture) == 0)
                    {
                        stat.Blocks = blockMapBytes.Length / stat.BlockSize + blockMapBytes.Length % stat.BlockSize;
                        stat.Length = blockMapBytes.Length;
                    }
                    else if (string.Compare(path, "$Boot", StringComparison.InvariantCulture) == 0 && bootBlocks != null)
                    {
                        stat.Blocks = bootBlocks.Length / stat.BlockSize + bootBlocks.Length % stat.BlockSize;
                        stat.Length = bootBlocks.Length;
                    }
                    else if (string.Compare(path, "$MDB", StringComparison.InvariantCulture) == 0)
                    {
                        stat.Blocks = mdbBlocks.Length / stat.BlockSize + mdbBlocks.Length % stat.BlockSize;
                        stat.Length = mdbBlocks.Length;
                    }
                    else
                    {
                        return(Errno.InvalidArgument);
                    }

                    return(Errno.NoError);
                }
            }

            if (!filenameToId.TryGetValue(path.ToLowerInvariant(), out uint fileId))
            {
                return(Errno.NoSuchFile);
            }

            if (!idToEntry.TryGetValue(fileId, out MFS_FileEntry entry))
            {
                return(Errno.NoSuchFile);
            }

            Errno error = GetAttributes(path, out FileAttributes attr);

            if (error != Errno.NoError)
            {
                return(error);
            }

            stat = new FileEntryInfo
            {
                Attributes    = attr,
                Blocks        = entry.flLgLen / volMDB.drAlBlkSiz,
                BlockSize     = volMDB.drAlBlkSiz,
                CreationTime  = DateHandlers.MacToDateTime(entry.flCrDat),
                DeviceNo      = 0,
                GID           = 0,
                Inode         = entry.flFlNum,
                LastWriteTime = DateHandlers.MacToDateTime(entry.flMdDat),
                Length        = entry.flPyLen,
                Links         = 1,
                Mode          = 0x124,
                UID           = 0
            };

            return(Errno.NoError);
        }
예제 #17
0
 /// <summary>
 /// Get the exception to throw for errno.
 /// </summary>
 /// <param name="errno">The errno to get an exception for.</param>
 /// <param name="throwForGeneric">Throw exception for general, Mono supported exceptions.</param>
 /// <returns>The exeption to throw, or null if there was no exception.</returns>
 public static Exception GetExceptionForErrno(Errno errno, bool throwForGeneric = false)
 {
     if (NativeConvert.FromErrno(errno) == 0)
     {
         return null;
     }
     switch (errno)
     {
         case Errno.ENOMEM:
             return new OutOfMemoryException();
         case Errno.EEXIST:
             return new IOException("File already exists", NativeConvert.FromErrno(errno));
         case Errno.EMFILE:
             return new IOException("Too many files open", NativeConvert.FromErrno(errno));
         case Errno.ENOTTY:
             return new IOException("Inappropriate I/O control operation", NativeConvert.FromErrno(errno));
         case Errno.EFBIG:
             return new IOException("File too large", NativeConvert.FromErrno(errno));
         case Errno.EPIPE:
             return new PipeException("Broken pipe", NativeConvert.FromErrno(errno));
         case ((Errno)47): //ECANCELED
             return new OperationCanceledException();
         case ((Errno)48): //ENOTSUP
             return new NotSupportedException();
     }
     if (throwForGeneric)
     {
         Mono.Unix.UnixMarshal.ThrowExceptionForError(errno);
         return null; //Will never reach here
     }
     else
     {
         // Nasty hack to actually get exception
         try
         {
             Mono.Unix.UnixMarshal.ThrowExceptionForError(errno);
             return new InvalidOperationException(Mono.Unix.UnixMarshal.GetErrorDescription(errno)); // Backup if no exception gets thrown.
         }
         catch (Exception e)
         {
             return e;
         }
     }
 }
예제 #18
0
 public static bool TryFromErrno(Errno value, out Int32 rval)
 {
     return(FromErrno(value, out rval) == 0);
 }
예제 #19
0
		public static long fpathconf (int filedes, PathconfName name, Errno defaultError)
		{
			throw new System.NotImplementedException();
		}
예제 #20
0
 public PosixException(Errno error) : base(error.Describe())
 {
     m_error = error;
 }
예제 #21
0
		public static long pathconf (
		string path, PathconfName name, Errno defaultError)
		{
			throw new System.NotImplementedException();
		}
예제 #22
0
	// Constructors.
	public IOException()
		: base(_("Exception_IO"))
		{
			errno = Errno.EIO;
		}
예제 #23
0
		public static long sysconf (SysconfName name, Errno defaultError)
		{
			throw new System.NotImplementedException();
		}
예제 #24
0
	// Internal constructors that are used to set correct error codes.
	internal IOException(Errno errno)
		: base(null)
		{
			this.errno = errno;
		}
예제 #25
0
        public Errno Read(string path, long offset, long size, ref byte[] buf)
        {
            if (!mounted)
            {
                return(Errno.AccessDenied);
            }

            Errno err = Stat(path, out FileEntryInfo stat);

            if (err != Errno.NoError)
            {
                return(err);
            }

            if (stat.Attributes.HasFlag(FileAttributes.Directory) && !debug)
            {
                return(Errno.IsDirectory);
            }

            if (offset >= stat.Length)
            {
                return(Errno.InvalidArgument);
            }

            if (size + offset >= stat.Length)
            {
                size = stat.Length - offset;
            }

            uint[] clusters = GetClusters((uint)stat.Inode);

            long firstCluster    = offset / bytesPerCluster;
            long offsetInCluster = offset % bytesPerCluster;
            long sizeInClusters  = (size + offsetInCluster) / bytesPerCluster;

            if ((size + offsetInCluster) % bytesPerCluster > 0)
            {
                sizeInClusters++;
            }

            MemoryStream ms = new MemoryStream();

            for (int i = 0; i < sizeInClusters; i++)
            {
                if (i + firstCluster >= clusters.Length)
                {
                    return(Errno.InvalidArgument);
                }

                byte[] buffer =
                    imagePlugin.ReadSectors(firstClusterSector + (clusters[i + firstCluster] - 1) * sectorsPerCluster,
                                            sectorsPerCluster);

                ms.Write(buffer, 0, buffer.Length);
            }

            ms.Position = offsetInCluster;
            buf         = new byte[size];
            ms.Read(buf, 0, (int)size);

            return(Errno.NoError);
        }
예제 #26
0
	extern public static String GetErrnoMessage(Errno errno);
예제 #27
0
        /// <summary>
        ///     Mounts an Apple DOS filesystem
        /// </summary>
        public Errno Mount(IMediaImage imagePlugin, Partition partition, Encoding encoding,
                           Dictionary <string, string> options)
        {
            device   = imagePlugin;
            start    = partition.Start;
            Encoding = encoding ?? new Apple2();

            if (device.Info.Sectors != 455 && device.Info.Sectors != 560)
            {
                DicConsole.DebugWriteLine("Apple DOS plugin", "Incorrect device size.");
                return(Errno.InOutError);
            }

            if (start > 0)
            {
                DicConsole.DebugWriteLine("Apple DOS plugin", "Partitions are not supported.");
                return(Errno.InOutError);
            }

            if (device.Info.SectorSize != 256)
            {
                DicConsole.DebugWriteLine("Apple DOS plugin", "Incorrect sector size.");
                return(Errno.InOutError);
            }

            sectorsPerTrack = device.Info.Sectors == 455 ? 13 : 16;

            // Read the VTOC
            vtocBlocks = device.ReadSector((ulong)(17 * sectorsPerTrack));
            vtoc       = new Vtoc();
            IntPtr vtocPtr = Marshal.AllocHGlobal(256);

            Marshal.Copy(vtocBlocks, 0, vtocPtr, 256);
            vtoc = (Vtoc)Marshal.PtrToStructure(vtocPtr, typeof(Vtoc));
            Marshal.FreeHGlobal(vtocPtr);

            track1UsedByFiles = false;
            track2UsedByFiles = false;
            usedSectors       = 1;

            Errno error = ReadCatalog();

            if (error != Errno.NoError)
            {
                DicConsole.DebugWriteLine("Apple DOS plugin", "Unable to read catalog.");
                return(error);
            }

            error = CacheAllFiles();
            if (error != Errno.NoError)
            {
                DicConsole.DebugWriteLine("Apple DOS plugin", "Unable cache all files.");
                return(error);
            }

            // Create XML metadata for mounted filesystem
            XmlFsType = new FileSystemType
            {
                Bootable              = true,
                Clusters              = (long)device.Info.Sectors,
                ClusterSize           = vtoc.bytesPerSector,
                Files                 = catalogCache.Count,
                FilesSpecified        = true,
                FreeClustersSpecified = true,
                Type = "Apple DOS"
            };
            XmlFsType.FreeClusters = XmlFsType.Clusters - usedSectors;

            if (options == null)
            {
                options = GetDefaultOptions();
            }
            if (options.TryGetValue("debug", out string debugString))
            {
                bool.TryParse(debugString, out debug);
            }
            mounted = true;
            return(Errno.NoError);
        }
예제 #28
0
		private static extern int ToErrno (Int32 value, out Errno rval);
        /// <summary>
        /// Retrieves the error information from the native implementation and constructs a new <see cref="NativeException"/> object, that can be thrown afterwards.
        /// </summary>
        /// <param name="nativeMethodName">Name of the native API method which returned the error code.</param>
        /// <param name="errorCode">The error code returned by the native API method.</param>
        /// <param name="errnoResolvable">This will tell whether the retrieved errno could be resolved into a symbolic representation.</param>
        /// <param name="errnoSymbolic">This will hold the symbolic value of the retrieved errno; check the <paramref name="errnoResolvable"/> parameter beforehand!</param>
        private NativeException RetrieveErrnoAndBuildException(string nativeMethodName, NativeErrorCodes errorCode, out bool errnoResolvable, out Errno errnoSymbolic)
        {
            // Retrieve errno
            var  errnoStringBuffer = new StringBuilder(256);
            long errno             = GetLastErrnoValue(errnoStringBuffer, errnoStringBuffer.Capacity);

            // Try to resolve to symbolic representation
            errnoResolvable = NativeConvert.TryToErrno((int)errno, out errnoSymbolic);

            // Create native exception object
            return(new NativeException(nativeMethodName, errorCode, errno, (errnoResolvable ? errnoSymbolic.ToString() + ", " : "") + errnoStringBuffer.ToString()));
        }
예제 #30
0
        Errno ReadFile(short fileId, out byte[] buf, bool tags)
        {
            buf = null;
            if (!mounted)
            {
                return(Errno.AccessDenied);
            }

            tags &= debug;

            if (fileId < 4 || fileId == 4 && mddf.fsversion != LISA_V2 && mddf.fsversion != LISA_V1)
            {
                return(Errno.InvalidArgument);
            }

            if (!tags && fileCache.TryGetValue(fileId, out buf))
            {
                return(Errno.NoError);
            }

            Errno error = ReadExtentsFile(fileId, out ExtentFile file);

            if (error != Errno.NoError)
            {
                return(error);
            }

            int sectorSize;

            if (tags)
            {
                sectorSize = devTagSize;
            }
            else
            {
                sectorSize = (int)device.Info.SectorSize;
            }

            byte[] temp = new byte[file.length * sectorSize];

            int offset = 0;

            for (int i = 0; i < file.extents.Length; i++)
            {
                byte[] sector;

                if (!tags)
                {
                    sector = device.ReadSectors((ulong)file.extents[i].start + mddf.mddf_block + volumePrefix,
                                                (uint)file.extents[i].length);
                }
                else
                {
                    sector = device.ReadSectorsTag((ulong)file.extents[i].start + mddf.mddf_block + volumePrefix,
                                                   (uint)file.extents[i].length, SectorTagType.AppleSectorTag);
                }

                Array.Copy(sector, 0, temp, offset, sector.Length);
                offset += sector.Length;
            }

            if (!tags)
            {
                if (fileSizeCache.TryGetValue(fileId, out int realSize))
                {
                    if (realSize > temp.Length)
                    {
                        DicConsole.ErrorWriteLine("File {0} gets truncated.", fileId);
                    }
                }
                buf = temp;

                fileCache.Add(fileId, buf);
            }
            else
            {
                buf = temp;
            }

            return(Errno.NoError);
        }
예제 #31
0
        protected void OnMenuOpen(object sender, EventArgs e)
        {
            // TODO: Extensions
            OpenFileDialog dlgOpenImage = new OpenFileDialog {
                Title = "Choose image to open"
            };

            DialogResult result = dlgOpenImage.ShowDialog(this);

            if (result != DialogResult.Ok)
            {
                return;
            }

            FiltersList filtersList = new FiltersList();
            IFilter     inputFilter = filtersList.GetFilter(dlgOpenImage.FileName);

            if (inputFilter == null)
            {
                MessageBox.Show("Cannot open specified file.", MessageBoxType.Error);
                return;
            }

            try
            {
                IMediaImage imageFormat = ImageFormat.Detect(inputFilter);

                if (imageFormat == null)
                {
                    MessageBox.Show("Image format not identified.", MessageBoxType.Error);
                    return;
                }

                DicConsole.WriteLine("Image format identified by {0} ({1}).", imageFormat.Name, imageFormat.Id);

                try
                {
                    if (!imageFormat.Open(inputFilter))
                    {
                        MessageBox.Show("Unable to open image format", MessageBoxType.Error);
                        DicConsole.ErrorWriteLine("Unable to open image format");
                        DicConsole.ErrorWriteLine("No error given");
                        return;
                    }

                    // TODO: SVG
                    Stream logo =
                        ResourceHandler
                        .GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{imageFormat.Info.MediaType}.png");

                    TreeGridItem imageGridItem = new TreeGridItem
                    {
                        Values = new object[]
                        {
                            logo == null ? null : new Bitmap(logo),
                            $"{Path.GetFileName(dlgOpenImage.FileName)} ({imageFormat.Info.MediaType})",
                            dlgOpenImage.FileName,
                            new pnlImageInfo(dlgOpenImage.FileName, inputFilter, imageFormat), inputFilter,
                            imageFormat
                        }
                    };

                    List <Partition> partitions = Core.Partitions.GetAll(imageFormat);
                    Core.Partitions.AddSchemesToStats(partitions);

                    bool          checkraw = false;
                    List <string> idPlugins;
                    IFilesystem   plugin;
                    PluginBase    plugins = GetPluginBase.Instance;

                    if (partitions.Count == 0)
                    {
                        DicConsole.DebugWriteLine("Analyze command", "No partitions found");

                        checkraw = true;
                    }
                    else
                    {
                        DicConsole.WriteLine("{0} partitions found.", partitions.Count);

                        foreach (string scheme in partitions.Select(p => p.Scheme).Distinct().OrderBy(s => s))
                        {
                            TreeGridItem schemeGridItem = new TreeGridItem
                            {
                                Values = new object[]
                                {
                                    nullImage, // TODO: Add icons to partition schemes
                                    scheme
                                }
                            };

                            foreach (Partition partition in partitions
                                     .Where(p => p.Scheme == scheme).OrderBy(p => p.Start))
                            {
                                TreeGridItem partitionGridItem = new TreeGridItem
                                {
                                    Values = new object[]
                                    {
                                        nullImage, // TODO: Add icons to partition schemes
                                        $"{partition.Name} ({partition.Type})", null, new pnlPartition(partition)
                                    }
                                };

                                DicConsole.WriteLine("Identifying filesystem on partition");

                                Core.Filesystems.Identify(imageFormat, out idPlugins, partition);
                                if (idPlugins.Count == 0)
                                {
                                    DicConsole.WriteLine("Filesystem not identified");
                                }
                                else
                                {
                                    DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins");

                                    foreach (string pluginName in idPlugins)
                                    {
                                        if (plugins.PluginsList.TryGetValue(pluginName, out plugin))
                                        {
                                            plugin.GetInformation(imageFormat, partition, out string information, null);

                                            IReadOnlyFilesystem fsPlugin = plugin as IReadOnlyFilesystem;

                                            if (fsPlugin != null)
                                            {
                                                Errno error =
                                                    fsPlugin.Mount(imageFormat, partition, null,
                                                                   new Dictionary <string, string>(), null);

                                                if (error != Errno.NoError)
                                                {
                                                    fsPlugin = null;
                                                }
                                            }

                                            TreeGridItem filesystemGridItem = new TreeGridItem
                                            {
                                                Values = new object[]
                                                {
                                                    nullImage, // TODO: Add icons to filesystems
                                                    plugin.XmlFsType.VolumeName is null
                                                        ? $"{plugin.XmlFsType.Type}"
                                                        : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})",
                                                    fsPlugin, new pnlFilesystem(plugin.XmlFsType, information)
                                                }
                                            };

                                            if (fsPlugin != null)
                                            {
                                                Statistics.AddCommand("ls");
                                                filesystemGridItem.Children.Add(placeholderItem);
                                            }

                                            Statistics.AddFilesystem(plugin.XmlFsType.Type);
                                            partitionGridItem.Children.Add(filesystemGridItem);
                                        }
                                    }
                                }

                                schemeGridItem.Children.Add(partitionGridItem);
                            }

                            imageGridItem.Children.Add(schemeGridItem);
                        }
                    }

                    if (checkraw)
                    {
                        Partition wholePart = new Partition
                        {
                            Name   = "Whole device",
                            Length = imageFormat.Info.Sectors,
                            Size   = imageFormat.Info.Sectors * imageFormat.Info.SectorSize
                        };

                        Core.Filesystems.Identify(imageFormat, out idPlugins, wholePart);
                        if (idPlugins.Count == 0)
                        {
                            DicConsole.WriteLine("Filesystem not identified");
                        }
                        else
                        {
                            DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins");

                            foreach (string pluginName in idPlugins)
                            {
                                if (plugins.PluginsList.TryGetValue(pluginName, out plugin))
                                {
                                    plugin.GetInformation(imageFormat, wholePart, out string information, null);

                                    IReadOnlyFilesystem fsPlugin = plugin as IReadOnlyFilesystem;

                                    if (fsPlugin != null)
                                    {
                                        Errno error = fsPlugin.Mount(imageFormat, wholePart, null,
                                                                     new Dictionary <string, string>(), null);

                                        if (error != Errno.NoError)
                                        {
                                            fsPlugin = null;
                                        }
                                    }

                                    TreeGridItem filesystemGridItem = new TreeGridItem
                                    {
                                        Values = new object[]
                                        {
                                            nullImage, // TODO: Add icons to filesystems
                                            plugin.XmlFsType.VolumeName is null
                                                ? $"{plugin.XmlFsType.Type}"
                                                : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})",
                                            fsPlugin, new pnlFilesystem(plugin.XmlFsType, information)
                                        }
                                    };

                                    if (fsPlugin != null)
                                    {
                                        Statistics.AddCommand("ls");
                                        filesystemGridItem.Children.Add(placeholderItem);
                                    }

                                    Statistics.AddFilesystem(plugin.XmlFsType.Type);
                                    imageGridItem.Children.Add(filesystemGridItem);
                                }
                            }
                        }
                    }

                    imagesRoot.Children.Add(imageGridItem);
                    treeImages.ReloadData();

                    Statistics.AddMediaFormat(imageFormat.Format);
                    Statistics.AddMedia(imageFormat.Info.MediaType, false);
                    Statistics.AddFilter(inputFilter.Name);
                }
예제 #32
0
        static void ExtractFilesInDir(string path, IReadOnlyFilesystem fs, string volumeName, string outputDir,
                                      bool doXattrs)
        {
            if (path.StartsWith('/'))
            {
                path = path.Substring(1);
            }

            Errno error = fs.ReadDir(path, out List <string> directory);

            if (error != Errno.NoError)
            {
                AaruConsole.ErrorWriteLine("Error {0} reading root directory {0}", error.ToString());

                return;
            }

            foreach (string entry in directory)
            {
                error = fs.Stat(path + "/" + entry, out FileEntryInfo stat);

                if (error == Errno.NoError)
                {
                    string outputPath;

                    if (stat.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        Directory.CreateDirectory(Path.Combine(outputDir, fs.XmlFsType.Type, volumeName));

                        outputPath = Path.Combine(outputDir, fs.XmlFsType.Type, volumeName, path, entry);

                        Directory.CreateDirectory(outputPath);

                        AaruConsole.WriteLine("Created subdirectory at {0}", outputPath);

                        ExtractFilesInDir(path + "/" + entry, fs, volumeName, outputDir, doXattrs);

                        var di = new DirectoryInfo(outputPath);

                        #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                        try
                        {
                            if (stat.CreationTimeUtc.HasValue)
                            {
                                di.CreationTimeUtc = stat.CreationTimeUtc.Value;
                            }
                        }
                        catch
                        {
                            // ignored
                        }

                        try
                        {
                            if (stat.LastWriteTimeUtc.HasValue)
                            {
                                di.LastWriteTimeUtc = stat.LastWriteTimeUtc.Value;
                            }
                        }
                        catch
                        {
                            // ignored
                        }

                        try
                        {
                            if (stat.AccessTimeUtc.HasValue)
                            {
                                di.LastAccessTimeUtc = stat.AccessTimeUtc.Value;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                        #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body

                        continue;
                    }

                    FileStream outputFile;

                    if (doXattrs)
                    {
                        error = fs.ListXAttr(path + "/" + entry, out List <string> xattrs);

                        if (error == Errno.NoError)
                        {
                            foreach (string xattr in xattrs)
                            {
                                byte[] xattrBuf = new byte[0];
                                error = fs.GetXattr(path + "/" + entry, xattr, ref xattrBuf);

                                if (error != Errno.NoError)
                                {
                                    continue;
                                }

                                Directory.CreateDirectory(Path.Combine(outputDir, fs.XmlFsType.Type, volumeName,
                                                                       ".xattrs", xattr));

                                outputPath = Path.Combine(outputDir, fs.XmlFsType.Type, volumeName, ".xattrs", xattr,
                                                          path, entry);

                                if (!File.Exists(outputPath))
                                {
                                    outputFile = new FileStream(outputPath, FileMode.CreateNew, FileAccess.ReadWrite,
                                                                FileShare.None);

                                    outputFile.Write(xattrBuf, 0, xattrBuf.Length);
                                    outputFile.Close();
                                    var fi = new FileInfo(outputPath);
                                    #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                                    try
                                    {
                                        if (stat.CreationTimeUtc.HasValue)
                                        {
                                            fi.CreationTimeUtc = stat.CreationTimeUtc.Value;
                                        }
                                    }
                                    catch
                                    {
                                        // ignored
                                    }

                                    try
                                    {
                                        if (stat.LastWriteTimeUtc.HasValue)
                                        {
                                            fi.LastWriteTimeUtc = stat.LastWriteTimeUtc.Value;
                                        }
                                    }
                                    catch
                                    {
                                        // ignored
                                    }

                                    try
                                    {
                                        if (stat.AccessTimeUtc.HasValue)
                                        {
                                            fi.LastAccessTimeUtc = stat.AccessTimeUtc.Value;
                                        }
                                    }
                                    catch
                                    {
                                        // ignored
                                    }
                                    #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                                    AaruConsole.WriteLine("Written {0} bytes of xattr {1} from file {2} to {3}",
                                                          xattrBuf.Length, xattr, entry, outputPath);
                                }
                                else
                                {
                                    AaruConsole.ErrorWriteLine("Cannot write xattr {0} for {1}, output exists", xattr,
                                                               entry);
                                }
                            }
                        }
                    }

                    Directory.CreateDirectory(Path.Combine(outputDir, fs.XmlFsType.Type, volumeName));

                    outputPath = Path.Combine(outputDir, fs.XmlFsType.Type, volumeName, path, entry);

                    if (!File.Exists(outputPath))
                    {
                        byte[] outBuf = new byte[0];

                        error = fs.Read(path + "/" + entry, 0, stat.Length, ref outBuf);

                        if (error == Errno.NoError)
                        {
                            outputFile = new FileStream(outputPath, FileMode.CreateNew, FileAccess.ReadWrite,
                                                        FileShare.None);

                            outputFile.Write(outBuf, 0, outBuf.Length);
                            outputFile.Close();
                            var fi = new FileInfo(outputPath);
                            #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                            try
                            {
                                if (stat.CreationTimeUtc.HasValue)
                                {
                                    fi.CreationTimeUtc = stat.CreationTimeUtc.Value;
                                }
                            }
                            catch
                            {
                                // ignored
                            }

                            try
                            {
                                if (stat.LastWriteTimeUtc.HasValue)
                                {
                                    fi.LastWriteTimeUtc = stat.LastWriteTimeUtc.Value;
                                }
                            }
                            catch
                            {
                                // ignored
                            }

                            try
                            {
                                if (stat.AccessTimeUtc.HasValue)
                                {
                                    fi.LastAccessTimeUtc = stat.AccessTimeUtc.Value;
                                }
                            }
                            catch
                            {
                                // ignored
                            }
                            #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                            AaruConsole.WriteLine("Written {0} bytes of file {1} to {2}", outBuf.Length, entry,
                                                  outputPath);
                        }
                        else
                        {
                            AaruConsole.ErrorWriteLine("Error {0} reading file {1}", error, entry);
                        }
                    }
                    else
                    {
                        AaruConsole.ErrorWriteLine("Cannot write file {0}, output exists", entry);
                    }
                }
                else
                {
                    AaruConsole.ErrorWriteLine("Error reading file {0}", entry);
                }
            }
        }
예제 #33
0
        ContentsFileType SidecarFile(IReadOnlyFilesystem filesystem, string path, string filename, FileEntryInfo stat)
        {
            ContentsFileType file          = new ContentsFileType();
            Checksum         fileChkWorker = new Checksum();

            if (stat.AccessTimeUtc.HasValue)
            {
                file.accessTime          = stat.AccessTimeUtc.Value;
                file.accessTimeSpecified = true;
            }

            file.attributes = (ulong)stat.Attributes;

            if (stat.BackupTimeUtc.HasValue)
            {
                file.backupTime          = stat.BackupTimeUtc.Value;
                file.backupTimeSpecified = true;
            }

            if (stat.CreationTimeUtc.HasValue)
            {
                file.creationTime          = stat.CreationTimeUtc.Value;
                file.creationTimeSpecified = true;
            }

            if (stat.DeviceNo.HasValue)
            {
                file.deviceNumber          = stat.DeviceNo.Value;
                file.deviceNumberSpecified = true;
            }

            file.inode = stat.Inode;

            if (stat.LastWriteTimeUtc.HasValue)
            {
                file.lastWriteTime          = stat.LastWriteTimeUtc.Value;
                file.lastWriteTimeSpecified = true;
            }

            file.length = (ulong)stat.Length;
            file.links  = stat.Links;
            file.name   = filename;

            if (stat.GID.HasValue)
            {
                file.posixGroupId          = stat.GID.Value;
                file.posixGroupIdSpecified = true;
            }

            if (stat.Mode.HasValue)
            {
                file.posixMode          = stat.Mode.Value;
                file.posixModeSpecified = true;
            }

            if (stat.UID.HasValue)
            {
                file.posixUserId          = stat.UID.Value;
                file.posixUserIdSpecified = true;
            }

            if (stat.StatusChangeTimeUtc.HasValue)
            {
                file.statusChangeTime          = stat.StatusChangeTimeUtc.Value;
                file.statusChangeTimeSpecified = true;
            }

            byte[] data = new byte[0];
            if (stat.Length > 0)
            {
                long position = 0;
                UpdateStatus($"Hashing file {path}/{filename}...");
                InitProgress2();
                while (position < stat.Length - 1048576)
                {
                    if (aborted)
                    {
                        return(file);
                    }

                    data = new byte[1048576];
                    filesystem.Read(path + "/" + filename, position, 1048576, ref data);

                    UpdateProgress2("Hashing file byte {0} of {1}", position, stat.Length);

                    fileChkWorker.Update(data);

                    position += 1048576;
                }

                data = new byte[stat.Length - position];
                filesystem.Read(path + "/" + filename, position, stat.Length - position, ref data);

                UpdateProgress2("Hashing file byte {0} of {1}", position, stat.Length);

                fileChkWorker.Update(data);

                EndProgress();

                file.Checksums = fileChkWorker.End().ToArray();
            }
            else
            {
                file.Checksums = emptyChecksums;
            }

            Errno ret = filesystem.ListXAttr(path + "/" + filename, out List <string> xattrs);

            if (ret != Errno.NoError)
            {
                return(file);
            }

            List <ExtendedAttributeType> xattrTypes = new List <ExtendedAttributeType>();

            foreach (string xattr in xattrs)
            {
                ret = filesystem.GetXattr(path + "/" + filename, xattr, ref data);

                if (ret != Errno.NoError)
                {
                    continue;
                }

                Checksum xattrChkWorker = new Checksum();
                xattrChkWorker.Update(data);

                xattrTypes.Add(new ExtendedAttributeType
                {
                    Checksums = xattrChkWorker.End().ToArray(),
                    length    = (ulong)data.Length,
                    name      = xattr
                });
            }

            if (xattrTypes.Count > 0)
            {
                file.ExtendedAttributes = xattrTypes.OrderBy(x => x.name).ToArray();
            }

            return(file);
        }
예제 #34
0
        public Errno GetXattr(string path, string xattr, ref byte[] buf)
        {
            buf = null;

            if (!_mounted)
            {
                return(Errno.AccessDenied);
            }

            Errno err = GetFileEntry(path, out DecodedDirectoryEntry entry);

            if (err != Errno.NoError)
            {
                return(err);
            }

            switch (xattr)
            {
            case "org.iso.9660.ea":
                if (entry.XattrLength == 0)
                {
                    return(Errno.NoSuchExtendedAttribute);
                }

                if (entry.Extents is null)
                {
                    return(Errno.InvalidArgument);
                }

                buf = ReadSingleExtent(entry.XattrLength * _blockSize, entry.Extents[0].extent);

                return(Errno.NoError);

            case "org.iso.9660.AssociatedFile":
                if (entry.AssociatedFile is null)
                {
                    return(Errno.NoSuchExtendedAttribute);
                }

                if (entry.AssociatedFile.Extents is null)
                {
                    return(Errno.InvalidArgument);
                }

                if (entry.AssociatedFile.Size == 0)
                {
                    buf = new byte[0];

                    return(Errno.NoError);
                }

                buf = ReadWithExtents(0, (long)entry.AssociatedFile.Size, entry.AssociatedFile.Extents,
                                      entry.AssociatedFile.XA?.signature == XA_MAGIC &&
                                      entry.AssociatedFile.XA?.attributes.HasFlag(XaAttributes.Interleaved) == true,
                                      entry.AssociatedFile.XA?.filenumber ?? 0);

                return(Errno.NoError);

            //case "com.apple.dos.type":
            //    if(entry.AppleDosType is null)
            //        return Errno.NoSuchExtendedAttribute;

            //    buf    = new byte[1];
            //    buf[0] = entry.AppleDosType.Value;

            //    return Errno.NoError;
            //case "com.apple.prodos.type":
            //    if(entry.AppleProDosType is null)
            //        return Errno.NoSuchExtendedAttribute;

            //    buf = BitConverter.GetBytes(entry.AppleProDosType.Value);

            //    return Errno.NoError;
            case "com.apple.ResourceFork":
                if (entry.ResourceFork is null)
                {
                    return(Errno.NoSuchExtendedAttribute);
                }

                if (entry.ResourceFork.Extents is null)
                {
                    return(Errno.InvalidArgument);
                }

                if (entry.ResourceFork.Size == 0)
                {
                    buf = new byte[0];

                    return(Errno.NoError);
                }

                buf = ReadWithExtents(0, (long)entry.ResourceFork.Size, entry.ResourceFork.Extents,
                                      entry.ResourceFork.XA?.signature == XA_MAGIC &&
                                      entry.ResourceFork.XA?.attributes.HasFlag(XaAttributes.Interleaved) == true,
                                      entry.ResourceFork.XA?.filenumber ?? 0);

                return(Errno.NoError);

            //case "com.apple.FinderInfo":
            //    if(entry.FinderInfo is null)
            //        return Errno.NoSuchExtendedAttribute;

            //    buf = Marshal.StructureToByteArrayBigEndian(entry.FinderInfo.Value);

            //    return Errno.NoError;
            //case "com.apple.Macintosh.Icon":
            //    if(entry.AppleIcon is null)
            //        return Errno.NoSuchExtendedAttribute;

            //    buf = new byte[entry.AppleIcon.Length];
            //    Array.Copy(entry.AppleIcon, 0, buf, 0, entry.AppleIcon.Length);

            //    return Errno.NoError;
            //case "com.amiga.comments":
            //    if(entry.AmigaComment is null)
            //        return Errno.NoSuchExtendedAttribute;

            //    buf = new byte[entry.AmigaComment.Length];
            //    Array.Copy(entry.AmigaComment, 0, buf, 0, entry.AmigaComment.Length);

            //    return Errno.NoError;
            case "org.iso.mode2.subheader":
                buf = ReadSubheaderWithExtents(entry.Extents, false);

                return(Errno.NoError);

            case "org.iso.mode2.subheader.copy":
                buf = ReadSubheaderWithExtents(entry.Extents, true);

                return(Errno.NoError);

            default: return(Errno.NoSuchExtendedAttribute);
            }
        }
예제 #35
0
        DirectoryType SidecarDirectory(IReadOnlyFilesystem filesystem, string path, string filename, FileEntryInfo stat)
        {
            DirectoryType directory = new DirectoryType();

            if (stat.AccessTimeUtc.HasValue)
            {
                directory.accessTime          = stat.AccessTimeUtc.Value;
                directory.accessTimeSpecified = true;
            }

            directory.attributes = (ulong)stat.Attributes;

            if (stat.BackupTimeUtc.HasValue)
            {
                directory.backupTime          = stat.BackupTimeUtc.Value;
                directory.backupTimeSpecified = true;
            }

            if (stat.CreationTimeUtc.HasValue)
            {
                directory.creationTime          = stat.CreationTimeUtc.Value;
                directory.creationTimeSpecified = true;
            }

            if (stat.DeviceNo.HasValue)
            {
                directory.deviceNumber          = stat.DeviceNo.Value;
                directory.deviceNumberSpecified = true;
            }

            directory.inode = stat.Inode;

            if (stat.LastWriteTimeUtc.HasValue)
            {
                directory.lastWriteTime          = stat.LastWriteTimeUtc.Value;
                directory.lastWriteTimeSpecified = true;
            }

            directory.links = stat.Links;
            directory.name  = filename;

            if (stat.GID.HasValue)
            {
                directory.posixGroupId          = stat.GID.Value;
                directory.posixGroupIdSpecified = true;
            }

            if (stat.Mode.HasValue)
            {
                directory.posixMode          = stat.Mode.Value;
                directory.posixModeSpecified = true;
            }

            if (stat.UID.HasValue)
            {
                directory.posixUserId          = stat.UID.Value;
                directory.posixUserIdSpecified = true;
            }

            if (stat.StatusChangeTimeUtc.HasValue)
            {
                directory.statusChangeTime          = stat.StatusChangeTimeUtc.Value;
                directory.statusChangeTimeSpecified = true;
            }

            Errno ret = filesystem.ReadDir(path + "/" + filename, out List <string> dirents);

            if (ret != Errno.NoError)
            {
                return(null);
            }

            List <DirectoryType>    directories = new List <DirectoryType>();
            List <ContentsFileType> files       = new List <ContentsFileType>();

            foreach (string dirent in dirents)
            {
                ret = filesystem.Stat(path + "/" + filename + "/" + dirent, out FileEntryInfo entryStat);

                if (ret != Errno.NoError)
                {
                    DicConsole.DebugWriteLine("Create-Sidecar command", "Cannot stat {0}", dirent);
                    continue;
                }

                if (entryStat.Attributes.HasFlag(FileAttributes.Directory))
                {
                    directories.Add(SidecarDirectory(filesystem, path + "/" + filename, dirent, entryStat));
                    continue;
                }

                files.Add(SidecarFile(filesystem, path + "/" + filename, dirent, entryStat));
            }

            if (files.Count > 0)
            {
                directory.File = files.OrderBy(f => f.name).ToArray();
            }
            if (directories.Count > 0)
            {
                directory.Directory = directories.OrderBy(d => d.name).ToArray();
            }

            return(directory);
        }
예제 #36
0
 private static extern int FromErrno(Errno value, out Int32 rval);
예제 #37
0
        public Errno Stat(string path, out FileEntryInfo stat)
        {
            stat = null;

            string[] pathElements = path.Split(new[]
            {
                '/'
            }, StringSplitOptions.RemoveEmptyEntries);

            if (pathElements.Length != 1)
            {
                return(Errno.NotSupported);
            }

            if (_debug)
            {
                if (string.Compare(path, "$", StringComparison.InvariantCulture) == 0 ||
                    string.Compare(path, "$Boot", StringComparison.InvariantCulture) == 0)
                {
                    stat = new FileEntryInfo
                    {
                        Attributes = FileAttributes.System,
                        BlockSize  = _device.Info.SectorSize * _multiplier,
                        Links      = 1
                    };

                    if (string.Compare(path, "$", StringComparison.InvariantCulture) == 0)
                    {
                        stat.Blocks = (_catalogBlocks.Length / stat.BlockSize) +
                                      (_catalogBlocks.Length % stat.BlockSize);

                        stat.Length = _catalogBlocks.Length;
                    }
                    else
                    {
                        stat.Blocks = (_bootBlocks.Length / stat.BlockSize) + (_catalogBlocks.Length % stat.BlockSize);
                        stat.Length = _bootBlocks.Length;
                    }

                    return(Errno.NoError);
                }
            }

            Errno error = GetFileEntry(path, out PascalFileEntry entry);

            if (error != Errno.NoError)
            {
                return(error);
            }

            stat = new FileEntryInfo
            {
                Attributes       = FileAttributes.File,
                Blocks           = entry.LastBlock - entry.FirstBlock,
                BlockSize        = _device.Info.SectorSize * _multiplier,
                LastWriteTimeUtc = DateHandlers.UcsdPascalToDateTime(entry.ModificationTime),
                Length           = ((entry.LastBlock - entry.FirstBlock) * _device.Info.SectorSize * _multiplier) +
                                   entry.LastBytes,
                Links = 1
            };

            return(Errno.NoError);
        }
예제 #38
0
 private static extern int ToErrno(Int32 value, out Errno rval);
예제 #39
0
 // Constructors.
 public SocketException()
     : base(S._("IO_Socket"))
 {
     errno = Errno.EREMOTEIO;
 }
예제 #40
0
파일: Syscall.cs 프로젝트: xaimaran/ravendb
 public static extern long sysconf(int name, Errno defaultError);
예제 #41
0
 protected SocketException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     errno = Errno.EREMOTEIO;
 }
예제 #42
0
 internal SocketException(String msg)
     : base(msg)
 {
     errno = Errno.EREMOTEIO;
 }
예제 #43
0
 internal SocketException(String msg, Exception inner)
     : base(msg, inner)
 {
     errno = Errno.EREMOTEIO;
 }
		private static int ToErrno (Int32 value, out Errno rval)
		{
			throw new System.NotImplementedException();
		}
예제 #45
0
        // Internal constructors that are used to set correct error codes.
        internal SocketException(Errno errno)
#if !ECMA_COMPAT
            : base((int)errno, DefaultMessage(null, errno))
#else
            : base(DefaultMessage(null, errno))
예제 #46
0
	public IOException(String msg)
		: base(msg)
		{
			errno = Errno.EIO;
		}
예제 #47
0
        protected static void SetLastError(Errno error)
        {
            int _error = NativeConvert.FromErrno(error);

            SetLastError(_error);
        }
예제 #48
0
	public IOException(String msg, int hresult)
		: base(msg)
		{
			errno = Errno.EIO;
			HResult = hresult;
		}
예제 #49
0
        }//onRestart

        //Execute an SWI instruction.
        /// <summary>
        /// Called when swi 0x00123456 is executed
        /// </summary>
        /// <param name="op_code">opcode being executed</param>
        /// <returns>number of cycles executed. 0 if none</returns>
        public uint Execute(uint op_code)
        {
            if ((op_code & 0x00ffffff) != 0x123456)
            {
                return(3);  // 3 cycles for an unhandled swi
            }
            try
            {
                uint r0 = mIhost.getReg(0);  // reason code

                //and execute based on the reason code.
                switch ((AngelSWI)r0)
                {
                case AngelSWI.Reason_Open:
                    r0 = swiOpen();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Close:
                    r0 = swiClose();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Write:
                    r0 = swiWrite();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Read:
                    r0 = swiRead();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_IsTTY:
                    r0 = swiIsTTy();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Seek:
                    r0 = swiSeek();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_FLen:
                    r0 = swiFlen();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Errno:
                    mIhost.setReg(0, (uint)mErrno);
                    break;

                case AngelSWI.Reason_Remove:
                    r0 = swiRemove();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Rename:
                    r0 = swiRename();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Clock:
                    r0 = SwiClock();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_Time:
                    r0 = SwiTime();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_HeapInfo:
                    r0 = HeapInfo();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_TmpNam:
                    r0 = TmpNam();
                    mIhost.setReg(0, r0);
                    break;

                case AngelSWI.Reason_WriteC:
                case AngelSWI.Reason_Write0:
                case AngelSWI.Reason_ReadC:
                case AngelSWI.Reason_System:
                case AngelSWI.Reason_GetCmdLine:
                case AngelSWI.Reason_EnterSVC:
                    mErrno = Errno.ENOTSUP;
                    mIhost.setReg(0, uint.MaxValue);
                    break;

                case AngelSWI.Reason_ReportException:
                    r0 = mIhost.getReg(1);
                    if (r0 != 0x0 && r0 != 0x20026)
                    {
                        // 20026 is a normal exit
                        // For convenience, we take 0 as a normal exit too
                        ARMPluginInterfaces.Utils.OutputDebugString(
                            "report exception SWI executed: 0x" + r0.ToString("x8"));
                    }
                    mIhost.HaltSimulation();
                    mIhost.GPR[15] -= 4;    //todo thumb mode?
                    this.closeAllStreams();
                    break;

                default:
                    //if it is an unknown reason then return 3 clock cycles executed but
                    //do no actual work. This prevents the swi exception from being raised
                    //for swi codes not handled here
                    ARMPluginInterfaces.Utils.OutputDebugString("unhandled Angel SWI code: " + r0.ToString());
                    break;
                } //switch
            }     //try
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception caught while processing SWI call, message:" + ex.Message);
                return(0);
            }
            return(3);
        }//Execute
예제 #50
0
	internal IOException(Errno errno, String msg)
		: base(msg)
		{
			this.errno = errno;
		}
예제 #51
0
        }//Execute

        // Open a file
        private uint swiOpen()
        {
            // Params:  filename, length of filename, mode
            // Result:  r0 = file handle
            if (!fetchParams(3))
            {
                return(errorCode(Errno.EFAULT));
            }

            try {
                string str    = ARMPluginInterfaces.Utils.loadStringFromMemory(mIhost, paramBlock[0], paramBlock[1]);
                uint   mode   = paramBlock[2];
                bool   binary = false;
                if ((mode & 1) != 0)
                {
                    binary = true;
                    mode  &= 0xffffffe;
                }
                if (binary)
                {
                    ARMPluginInterfaces.Utils.OutputDebugString("binary mode files unsupported");
                }

                mErrno = Errno.NONE;
                ARMSimStream astream = null;
                if (String.IsNullOrEmpty(str) || str == ":tt")
                {
                    // First three uses of this filename map to the standard streams
                    // stdin, stdout, & stderr which have already been opened
                    if (stdFileNum <= 2)
                    {
                        return(stdFileNum++);
                    }
                    // We want additional console windowss??
                    uint stdHandle = mIhost.CreateStandardConsole(str);
                    astream = new ARMSimConsoleStream(stdHandle, mIhost);
                }
                else
                {
                    string currDir = null;
                    if (mIhost.UserDirectory != null)
                    {
                        currDir = Directory.GetCurrentDirectory();
                        Directory.SetCurrentDirectory(mIhost.UserDirectory);
                    }
                    switch (mode)
                    {
                    case 0:      // read
                        astream = new InputARMSimFileStream(new StreamReader(File.OpenRead(str)));
                        break;

                    case 2:                     // read-write mode
                        mErrno = Errno.ENOTSUP; // unsupported mode
                        break;

                    case 4:      // write (with create or truncate)
                        astream = new OutputARMSimFileStream(new StreamWriter(File.Open(str, FileMode.OpenOrCreate)));
                        break;

                    case 8:      // write in append mode
                        astream = new OutputARMSimFileStream(new StreamWriter(File.Open(str, FileMode.Append)));
                        break;

                    default:
                        mErrno = Errno.EINVAL;      // invalid mode
                        break;
                    }
                    if (currDir != null)
                    {
                        Directory.SetCurrentDirectory(currDir);
                    }
                    if (mErrno != Errno.NONE)
                    {
                        return(uint.MaxValue);
                    }
                }
                int fileHandle = 0;
                // search for the first available handle
                while (fileHandle < mFiles.Count)
                {
                    if (mFiles[fileHandle] == null)
                    {
                        mFiles[fileHandle] = astream;
                        return((uint)fileHandle);
                    }
                    fileHandle++;
                }
                mFiles.Add(astream);
                return((uint)fileHandle);
            } catch (Exception) {
                return(errorCode(Errno.EIO));
            }
        }
예제 #52
0
	// Get the message that corresponds to a platform error number.
	internal static String GetErrnoMessage(Errno errno)
			{
				// Try getting a message from the underlying platform.
				String str = FileMethods.GetErrnoMessage(errno);
				if(str != null)
				{
					return str;
				}

				// Use the default I/O exception string.
				return _("Exception_IO");
			}
예제 #53
0
 private uint errorCode(Errno code)
 {
     mErrno = code;
     return(uint.MaxValue);
 }
예제 #54
0
		private static sock.SocketException GetException (Errno error)
		{
			if (error == Errno.EAGAIN ||
				error == Errno.EWOULDBLOCK) // WSAEWOULDBLOCK
				return new sock.SocketException (10035);
			
			if (error == Errno.EBADF ||
				error == Errno.ENOTSOCK) // WSAENOTSOCK
				return new sock.SocketException (10038);
			
			if (error == Errno.ECONNABORTED) // WSAENETDOWN
				return new sock.SocketException (10050);
			
			if (error == Errno.EINVAL) // WSAEINVAL
				return new sock.SocketException (10022);
			
			return new sock.SocketException ();
		}
예제 #55
0
        /// <summary>
        ///     Mounts an Apple Lisa filesystem
        /// </summary>
        public Errno Mount(IMediaImage imagePlugin, Partition partition, Encoding encoding,
                           Dictionary <string, string> options)
        {
            try
            {
                device   = imagePlugin;
                Encoding = new LisaRoman();

                // Lisa OS is unable to work on disks without tags.
                // This code is designed like that.
                // However with some effort the code may be modified to ignore them.
                if (device.Info.ReadableSectorTags == null ||
                    !device.Info.ReadableSectorTags.Contains(SectorTagType.AppleSectorTag))
                {
                    DicConsole.DebugWriteLine("LisaFS plugin", "Underlying device does not support Lisa tags");
                    return(Errno.InOutError);
                }

                // LisaOS is big-endian
                BigEndianBitConverter.IsLittleEndian = BitConverter.IsLittleEndian;

                // Minimal LisaOS disk is 3.5" single sided double density, 800 sectors
                if (device.Info.Sectors < 800)
                {
                    DicConsole.DebugWriteLine("LisaFS plugin", "Device is too small");
                    return(Errno.InOutError);
                }

                // MDDF cannot be at end of device, of course
                volumePrefix = device.Info.Sectors;

                // LisaOS searches sectors until tag tells MDDF resides there, so we'll search 100 sectors
                for (ulong i = 0; i < 100; i++)
                {
                    DecodeTag(device.ReadSectorTag(i, SectorTagType.AppleSectorTag), out LisaTag.PriamTag searchTag);

                    DicConsole.DebugWriteLine("LisaFS plugin", "Sector {0}, file ID 0x{1:X4}", i, searchTag.FileId);

                    if (volumePrefix == device.Info.Sectors && searchTag.FileId == FILEID_LOADER_SIGNED)
                    {
                        volumePrefix = i - 1;
                    }

                    if (searchTag.FileId != FILEID_MDDF)
                    {
                        continue;
                    }

                    devTagSize = device.ReadSectorTag(i, SectorTagType.AppleSectorTag).Length;

                    byte[] sector = device.ReadSector(i);
                    mddf = new MDDF();
                    byte[] pString = new byte[33];
                    uint   lisaTime;

                    mddf.fsversion = BigEndianBitConverter.ToUInt16(sector, 0x00);
                    mddf.volid     = BigEndianBitConverter.ToUInt64(sector, 0x02);
                    mddf.volnum    = BigEndianBitConverter.ToUInt16(sector, 0x0A);
                    Array.Copy(sector, 0x0C, pString, 0, 33);
                    mddf.volname  = StringHandlers.PascalToString(pString, Encoding);
                    mddf.unknown1 = sector[0x2D];
                    Array.Copy(sector, 0x2E, pString, 0, 33);
                    // Prevent garbage
                    mddf.password =
                        pString[0] <= 32 ? StringHandlers.PascalToString(pString, Encoding) : "";
                    mddf.unknown2                     = sector[0x4F];
                    mddf.machine_id                   = BigEndianBitConverter.ToUInt32(sector, 0x50);
                    mddf.master_copy_id               = BigEndianBitConverter.ToUInt32(sector, 0x54);
                    lisaTime                          = BigEndianBitConverter.ToUInt32(sector, 0x58);
                    mddf.dtvc                         = DateHandlers.LisaToDateTime(lisaTime);
                    lisaTime                          = BigEndianBitConverter.ToUInt32(sector, 0x5C);
                    mddf.dtcc                         = DateHandlers.LisaToDateTime(lisaTime);
                    lisaTime                          = BigEndianBitConverter.ToUInt32(sector, 0x60);
                    mddf.dtvb                         = DateHandlers.LisaToDateTime(lisaTime);
                    lisaTime                          = BigEndianBitConverter.ToUInt32(sector, 0x64);
                    mddf.dtvs                         = DateHandlers.LisaToDateTime(lisaTime);
                    mddf.unknown3                     = BigEndianBitConverter.ToUInt32(sector, 0x68);
                    mddf.mddf_block                   = BigEndianBitConverter.ToUInt32(sector, 0x6C);
                    mddf.volsize_minus_one            = BigEndianBitConverter.ToUInt32(sector, 0x70);
                    mddf.volsize_minus_mddf_minus_one = BigEndianBitConverter.ToUInt32(sector, 0x74);
                    mddf.vol_size                     = BigEndianBitConverter.ToUInt32(sector, 0x78);
                    mddf.blocksize                    = BigEndianBitConverter.ToUInt16(sector, 0x7C);
                    mddf.datasize                     = BigEndianBitConverter.ToUInt16(sector, 0x7E);
                    mddf.unknown4                     = BigEndianBitConverter.ToUInt16(sector, 0x80);
                    mddf.unknown5                     = BigEndianBitConverter.ToUInt32(sector, 0x82);
                    mddf.unknown6                     = BigEndianBitConverter.ToUInt32(sector, 0x86);
                    mddf.clustersize                  = BigEndianBitConverter.ToUInt16(sector, 0x8A);
                    mddf.fs_size                      = BigEndianBitConverter.ToUInt32(sector, 0x8C);
                    mddf.unknown7                     = BigEndianBitConverter.ToUInt32(sector, 0x90);
                    mddf.srec_ptr                     = BigEndianBitConverter.ToUInt32(sector, 0x94);
                    mddf.unknown9                     = BigEndianBitConverter.ToUInt16(sector, 0x98);
                    mddf.srec_len                     = BigEndianBitConverter.ToUInt16(sector, 0x9A);
                    mddf.unknown10                    = BigEndianBitConverter.ToUInt32(sector, 0x9C);
                    mddf.unknown11                    = BigEndianBitConverter.ToUInt32(sector, 0xA0);
                    mddf.unknown12                    = BigEndianBitConverter.ToUInt32(sector, 0xA4);
                    mddf.unknown13                    = BigEndianBitConverter.ToUInt32(sector, 0xA8);
                    mddf.unknown14                    = BigEndianBitConverter.ToUInt32(sector, 0xAC);
                    mddf.filecount                    = BigEndianBitConverter.ToUInt16(sector, 0xB0);
                    mddf.unknown15                    = BigEndianBitConverter.ToUInt32(sector, 0xB2);
                    mddf.unknown16                    = BigEndianBitConverter.ToUInt32(sector, 0xB6);
                    mddf.freecount                    = BigEndianBitConverter.ToUInt32(sector, 0xBA);
                    mddf.unknown17                    = BigEndianBitConverter.ToUInt16(sector, 0xBE);
                    mddf.unknown18                    = BigEndianBitConverter.ToUInt32(sector, 0xC0);
                    mddf.overmount_stamp              = BigEndianBitConverter.ToUInt64(sector, 0xC4);
                    mddf.serialization                = BigEndianBitConverter.ToUInt32(sector, 0xCC);
                    mddf.unknown19                    = BigEndianBitConverter.ToUInt32(sector, 0xD0);
                    mddf.unknown_timestamp            = BigEndianBitConverter.ToUInt32(sector, 0xD4);
                    mddf.unknown20                    = BigEndianBitConverter.ToUInt32(sector, 0xD8);
                    mddf.unknown21                    = BigEndianBitConverter.ToUInt32(sector, 0xDC);
                    mddf.unknown22                    = BigEndianBitConverter.ToUInt32(sector, 0xE0);
                    mddf.unknown23                    = BigEndianBitConverter.ToUInt32(sector, 0xE4);
                    mddf.unknown24                    = BigEndianBitConverter.ToUInt32(sector, 0xE8);
                    mddf.unknown25                    = BigEndianBitConverter.ToUInt32(sector, 0xEC);
                    mddf.unknown26                    = BigEndianBitConverter.ToUInt32(sector, 0xF0);
                    mddf.unknown27                    = BigEndianBitConverter.ToUInt32(sector, 0xF4);
                    mddf.unknown28                    = BigEndianBitConverter.ToUInt32(sector, 0xF8);
                    mddf.unknown29                    = BigEndianBitConverter.ToUInt32(sector, 0xFC);
                    mddf.unknown30                    = BigEndianBitConverter.ToUInt32(sector, 0x100);
                    mddf.unknown31                    = BigEndianBitConverter.ToUInt32(sector, 0x104);
                    mddf.unknown32                    = BigEndianBitConverter.ToUInt32(sector, 0x108);
                    mddf.unknown33                    = BigEndianBitConverter.ToUInt32(sector, 0x10C);
                    mddf.unknown34                    = BigEndianBitConverter.ToUInt32(sector, 0x110);
                    mddf.unknown35                    = BigEndianBitConverter.ToUInt32(sector, 0x114);
                    mddf.backup_volid                 = BigEndianBitConverter.ToUInt64(sector, 0x118);
                    mddf.label_size                   = BigEndianBitConverter.ToUInt16(sector, 0x120);
                    mddf.fs_overhead                  = BigEndianBitConverter.ToUInt16(sector, 0x122);
                    mddf.result_scavenge              = BigEndianBitConverter.ToUInt16(sector, 0x124);
                    mddf.boot_code                    = BigEndianBitConverter.ToUInt16(sector, 0x126);
                    mddf.boot_environ                 = BigEndianBitConverter.ToUInt16(sector, 0x6C);
                    mddf.unknown36                    = BigEndianBitConverter.ToUInt32(sector, 0x12A);
                    mddf.unknown37                    = BigEndianBitConverter.ToUInt32(sector, 0x12E);
                    mddf.unknown38                    = BigEndianBitConverter.ToUInt32(sector, 0x132);
                    mddf.vol_sequence                 = BigEndianBitConverter.ToUInt16(sector, 0x136);
                    mddf.vol_left_mounted             = sector[0x138];

                    // Check that the MDDF is correct
                    if (mddf.mddf_block != i - volumePrefix ||
                        mddf.vol_size > device.Info.Sectors ||
                        mddf.vol_size - 1 !=
                        mddf.volsize_minus_one ||
                        mddf.vol_size - i - 1 !=
                        mddf.volsize_minus_mddf_minus_one - volumePrefix ||
                        mddf.datasize >
                        mddf.blocksize || mddf.blocksize < device.Info.SectorSize ||
                        mddf.datasize != device.Info.SectorSize)
                    {
                        DicConsole.DebugWriteLine("LisaFS plugin", "Incorrect MDDF found");
                        return(Errno.InvalidArgument);
                    }

                    // Check MDDF version
                    switch (mddf.fsversion)
                    {
                    case LISA_V1:
                        DicConsole.DebugWriteLine("LisaFS plugin", "Mounting LisaFS v1");
                        break;

                    case LISA_V2:
                        DicConsole.DebugWriteLine("LisaFS plugin", "Mounting LisaFS v2");
                        break;

                    case LISA_V3:
                        DicConsole.DebugWriteLine("LisaFS plugin", "Mounting LisaFS v3");
                        break;

                    default:
                        DicConsole.ErrorWriteLine("Cannot mount LisaFS version {0}", mddf.fsversion.ToString());
                        return(Errno.NotSupported);
                    }

                    // Initialize caches
                    extentCache     = new Dictionary <short, ExtentFile>();
                    systemFileCache = new Dictionary <short, byte[]>();
                    fileCache       = new Dictionary <short, byte[]>();
                    //catalogCache = new Dictionary<short, List<CatalogEntry>>();
                    fileSizeCache = new Dictionary <short, int>();

                    mounted = true;
                    if (options == null)
                    {
                        options = GetDefaultOptions();
                    }
                    if (options.TryGetValue("debug", out string debugString))
                    {
                        bool.TryParse(debugString, out debug);
                    }

                    if (debug)
                    {
                        printedExtents = new List <short>();
                    }

                    // Read the S-Records file
                    Errno error = ReadSRecords();
                    if (error != Errno.NoError)
                    {
                        DicConsole.ErrorWriteLine("Error {0} reading S-Records file.", error);
                        return(error);
                    }

                    directoryDtcCache = new Dictionary <short, DateTime> {
                        { DIRID_ROOT, mddf.dtcc }
                    };

                    // Read the Catalog File
                    error = ReadCatalog();

                    if (error != Errno.NoError)
                    {
                        DicConsole.DebugWriteLine("LisaFS plugin", "Cannot read Catalog File, error {0}",
                                                  error.ToString());
                        mounted = false;
                        return(error);
                    }

                    // If debug, cache system files
                    if (debug)
                    {
                        error = ReadSystemFile(FILEID_BOOT_SIGNED, out _);
                        if (error != Errno.NoError)
                        {
                            DicConsole.DebugWriteLine("LisaFS plugin", "Unable to read boot blocks");
                            mounted = false;
                            return(error);
                        }

                        error = ReadSystemFile(FILEID_LOADER_SIGNED, out _);
                        if (error != Errno.NoError)
                        {
                            DicConsole.DebugWriteLine("LisaFS plugin", "Unable to read boot loader");
                            mounted = false;
                            return(error);
                        }

                        error = ReadSystemFile((short)FILEID_MDDF, out _);
                        if (error != Errno.NoError)
                        {
                            DicConsole.DebugWriteLine("LisaFS plugin", "Unable to read MDDF");
                            mounted = false;
                            return(error);
                        }

                        error = ReadSystemFile((short)FILEID_BITMAP, out _);
                        if (error != Errno.NoError)
                        {
                            DicConsole.DebugWriteLine("LisaFS plugin", "Unable to read volume bitmap");
                            mounted = false;
                            return(error);
                        }

                        error = ReadSystemFile((short)FILEID_SRECORD, out _);
                        if (error != Errno.NoError)
                        {
                            DicConsole.DebugWriteLine("LisaFS plugin", "Unable to read S-Records file");
                            mounted = false;
                            return(error);
                        }
                    }

                    // Create XML metadata for mounted filesystem
                    XmlFsType = new FileSystemType();
                    if (DateTime.Compare(mddf.dtvb, DateHandlers.LisaToDateTime(0)) > 0)
                    {
                        XmlFsType.BackupDate          = mddf.dtvb;
                        XmlFsType.BackupDateSpecified = true;
                    }

                    XmlFsType.Clusters    = mddf.vol_size;
                    XmlFsType.ClusterSize = mddf.clustersize * mddf.datasize;
                    if (DateTime.Compare(mddf.dtvc, DateHandlers.LisaToDateTime(0)) > 0)
                    {
                        XmlFsType.CreationDate          = mddf.dtvc;
                        XmlFsType.CreationDateSpecified = true;
                    }

                    XmlFsType.Dirty                 = mddf.vol_left_mounted != 0;
                    XmlFsType.Files                 = mddf.filecount;
                    XmlFsType.FilesSpecified        = true;
                    XmlFsType.FreeClusters          = mddf.freecount;
                    XmlFsType.FreeClustersSpecified = true;
                    XmlFsType.Type         = "LisaFS";
                    XmlFsType.VolumeName   = mddf.volname;
                    XmlFsType.VolumeSerial = $"{mddf.volid:X16}";

                    return(Errno.NoError);
                }

                DicConsole.DebugWriteLine("LisaFS plugin", "Not a Lisa filesystem");
                return(Errno.NotSupported);
            }
            catch (Exception ex)
            {
                DicConsole.ErrorWriteLine("Exception {0}, {1}, {2}", ex.Message, ex.InnerException, ex.StackTrace);
                return(Errno.InOutError);
            }
        }
예제 #56
0
		public static bool TryFromErrno (Errno value, out Int32 rval)
		{
			return FromErrno (value, out rval) == 0;
		}
예제 #57
0
        Errno GetAttributes(short fileId, out FileAttributes attributes)
        {
            attributes = new FileAttributes();
            if (!mounted)
            {
                return(Errno.AccessDenied);
            }

            if (fileId < 4)
            {
                if (!debug)
                {
                    return(Errno.NoSuchFile);
                }

                attributes  = new FileAttributes();
                attributes  = FileAttributes.System;
                attributes |= FileAttributes.Hidden;

                attributes |= FileAttributes.File;

                return(Errno.NoError);
            }

            Errno error = ReadExtentsFile(fileId, out ExtentFile extFile);

            if (error != Errno.NoError)
            {
                return(error);
            }

            switch (extFile.ftype)
            {
            case FileType.Spool:
                attributes |= FileAttributes.CharDevice;
                break;

            case FileType.UserCat:
            case FileType.RootCat:
                attributes |= FileAttributes.Directory;
                break;

            case FileType.Pipe:
                attributes |= FileAttributes.Pipe;
                break;

            case FileType.Undefined: break;

            default:
                attributes |= FileAttributes.File;
                attributes |= FileAttributes.Extents;
                break;
            }

            if (extFile.protect > 0)
            {
                attributes |= FileAttributes.Immutable;
            }
            if (extFile.locked > 0)
            {
                attributes |= FileAttributes.ReadOnly;
            }
            if (extFile.password_valid > 0)
            {
                attributes |= FileAttributes.Password;
            }

            return(Errno.NoError);
        }
예제 #58
0
		public static bool TryToErrno (Int32 value, out Errno rval)
		{
			return ToErrno (value, out rval) == 0;
		}
	// Constructors.
	public SocketException()
		: base(S._("IO_Socket"))
		{
			errno = Errno.EREMOTEIO;
		}