Exemplo n.º 1
0
        public void GetMethodFromSecondSuperClass()
        {
            DefinedClass proto = new DefinedClass("proto");
            DefinedClass super = new DefinedClass("object");
            IFunction method = new NativeMethod(this.DummyMethod);
            super.SetValue("foo", method);
            DefinedClass klass = new DefinedClass("Spam", new IType[] { proto, super });

            var result = klass.GetMethod("foo");
            Assert.IsNotNull(result);
            Assert.IsTrue(klass.HasMethod("foo"));
        }
Exemplo n.º 2
0
        public void DefineMethodUsingSetValue()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction method = new NativeMethod(this.DummyMethod);

            klass.SetValue("foo", method);

            var result = klass.GetMethod("foo");
            Assert.IsNotNull(result);
            Assert.AreEqual(method, result);
            Assert.IsTrue(klass.HasMethod("foo"));
            Assert.IsTrue(klass.HasValue("foo"));
        }
Exemplo n.º 3
0
        public void GetMethodFromClass()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction function = new NativeMethod(DummyMethod);
            klass.SetMethod("foo", function);
            DynamicObject dynobj = new DynamicObject(klass);

            var result = dynobj.GetValue("foo");

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(IFunction));
            Assert.AreEqual(function, result);
        }
Exemplo n.º 4
0
        public void InvokeGetValueMethod()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction function = new NativeMethod(GetValueMethod);
            klass.SetMethod("foo", function);
            DynamicObject dynobj = new DynamicObject(klass);
            dynobj.SetValue("one", 1);

            var result = dynobj.Invoke("foo", null, new object[] { "one" }, null);

            Assert.IsNotNull(result);
            Assert.AreEqual(1, result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Read the messages from a mailslot by using the mailslot handle in a call
        /// to the ReadFile function.
        /// </summary>
        /// <param name="hMailslot">The handle of the mailslot</param>
        /// <returns>
        /// If the function succeeds, the return value is true.
        /// </returns>
        static bool ReadMailslot(SafeMailslotHandle hMailslot)
        {
            int cbMessageBytes = 0;         // Size of the message in bytes
            int cbBytesRead    = 0;         // Number of bytes read from the mailslot
            int cMessages      = 0;         // Number of messages in the slot
            int nMessageId     = 0;         // Message ID

            bool succeeded = false;

            // Check for the number of messages in the mailslot.
            succeeded = NativeMethod.GetMailslotInfo(
                hMailslot,                  // Handle of the mailslot
                IntPtr.Zero,                // No maximum message size
                out cbMessageBytes,         // Size of next message
                out cMessages,              // Number of messages
                IntPtr.Zero                 // No read time-out
                );
            if (!succeeded)
            {
                Console.WriteLine("GetMailslotInfo failed w/err 0x{0:X}",
                                  Marshal.GetLastWin32Error());
                return(succeeded);
            }

            if (cbMessageBytes == MAILSLOT_NO_MESSAGE)
            {
                // There are no new messages in the mailslot at present
                Console.WriteLine("No new messages.");
                return(succeeded);
            }

            // Retrieve the messages one by one from the mailslot.
            while (cMessages != 0)
            {
                nMessageId++;

                // Declare a byte array to fetch the data
                byte[] bBuffer = new byte[cbMessageBytes];
                succeeded = NativeMethod.ReadFile(
                    hMailslot,              // Handle of mailslot
                    bBuffer,                // Buffer to receive data
                    cbMessageBytes,         // Size of buffer in bytes
                    out cbBytesRead,        // Number of bytes read from mailslot
                    IntPtr.Zero             // Not overlapped I/O
                    );
                if (!succeeded)
                {
                    Console.WriteLine("ReadFile failed w/err 0x{0:X}",
                                      Marshal.GetLastWin32Error());
                    break;
                }

                // Display the message.
                Console.WriteLine("Message #{0}: {1}", nMessageId,
                                  Encoding.Unicode.GetString(bBuffer));

                // Get the current number of un-read messages in the slot. The number
                // may not equal the initial message number because new messages may
                // arrive while we are reading the items in the slot.
                succeeded = NativeMethod.GetMailslotInfo(
                    hMailslot,              // Handle of the mailslot
                    IntPtr.Zero,            // No maximum message size
                    out cbMessageBytes,     // Size of next message
                    out cMessages,          // Number of messages
                    IntPtr.Zero             // No read time-out
                    );
                if (!succeeded)
                {
                    Console.WriteLine("GetMailslotInfo failed w/err 0x{0:X}",
                                      Marshal.GetLastWin32Error());
                    break;
                }
            }

            return(succeeded);
        }
Exemplo n.º 6
0
        /// <summary>Calls method <paramref name="method" /> in SuperMemo</summary>
        /// <param name="method">The method to call</param>
        /// <param name="parameters">The method's parameters to pass along with the call</param>
        /// <returns>
        ///   The returned value (eax register) from the call to <paramref name="method" />
        /// </returns>
        protected int CallNativeMethod(NativeMethod method,
                                       dynamic[]    parameters)
        {
            SMA.Debug($"Executing native method {Enum.GetName(typeof(NativeMethod), method)}.");

            if (parameters == null)
            {
                OnException(new ArgumentNullException(nameof(parameters), $"CallNativeMethod: Called with null 'parameters' for method {method}"));
                return(-1);
            }

            // Possible null reference on parameters
            var marshalledParameters = new IMarshalledValue[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var p             = parameters[i];
                var dynMarshalled = MarshalValue.Marshal(_smProcess, p);

                if (dynMarshalled is IMarshalledValue marshalled)
                {
                    marshalledParameters[i] = marshalled;
                }

                else
                {
                    OnException(new ArgumentException($"CallNativeMethod: Parameter n°{i} '{p}' could not be marshalled for method {method}",
                                                      nameof(p)));
                    return(-1);
                }
            }

            try
            {
                switch (method)
                {
                case NativeMethod.AppendAndAddElementFromText:
                    var elWdw  = marshalledParameters[0].Reference.ToInt32();
                    var elType = marshalledParameters[1].Reference.ToInt32();
                    var elDesc = marshalledParameters[2].Reference.ToInt32();

                    // elWdw.AppendElement(elType, automatic: false);
                    int elemId = Delphi.registerCall3(_callTable[NativeMethod.ElWdw_AppendElement],
                                                      elWdw,
                                                      elType,
                                                      0);

                    if (elemId <= 0)
                    {
                        return(-1);
                    }

                    // elWdw.AddElementFromText(elDesc);
                    int res = Delphi.registerCall2(_callTable[NativeMethod.ElWdw_AddElementFromText],
                                                   elWdw,
                                                   elDesc);

                    return(res > 0 ? elemId : -1);

                case NativeMethod.PostponeRepetition:
                    elWdw = marshalledParameters[0].Reference.ToInt32();
                    var interval = marshalledParameters[1].Reference.ToInt32();

                    // elWdw.ExecuteUncommittedRepetition(inclTopics: true, forceDisplay: false);
                    Delphi.registerCall3(_callTable[NativeMethod.ElWdw_ExecuteUncommittedRepetition],
                                         elWdw,
                                         1,
                                         0);

                    // elWdw.ScheduleInInterval(interval);
                    Delphi.registerCall2(_callTable[NativeMethod.ElWdw_ScheduleInInterval],
                                         elWdw,
                                         interval);

                    // elWdw.SetElementState(DisplayState.Display);
                    //registerCall2(_callTable[NativeMethod.ElWdw_SetElementState],
                    //              elWdw,
                    //              2);

                    // elWdw.NextElementInLearningQueue()
                    Delphi.registerCall1(_callTable[NativeMethod.ElWdw_NextElementInLearningQueue],
                                         elWdw);

                    return(1);

                case NativeMethod.ForceRepetitionAndResume:
                    elWdw    = marshalledParameters[0].Reference.ToInt32();
                    interval = marshalledParameters[1].Reference.ToInt32();
                    var adjustPriority = marshalledParameters[2].Reference.ToInt32();

                    // elWdw.ForceRepetitionExt(interval, adjustPriority);
                    Delphi.registerCall3(_callTable[NativeMethod.ElWdw_ForceRepetitionExt],
                                         elWdw,
                                         interval,
                                         adjustPriority);

                    // elWdw.NextElementInLearningQueue();
                    Delphi.registerCall1(_callTable[NativeMethod.ElWdw_NextElementInLearningQueue],
                                         elWdw);

                    // elWdw.RestoreLearningMode();
                    Delphi.registerCall1(_callTable[NativeMethod.ElWdw_RestoreLearningMode],
                                         elWdw);

                    return(1);
                }

                switch (parameters.Length)
                {
                case 1:
                    return(Delphi.registerCall1(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32()));

                case 2:
                    return(Delphi.registerCall2(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32(),
                                                marshalledParameters[1].Reference.ToInt32()));

                case 3:
                    return(Delphi.registerCall3(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32(),
                                                marshalledParameters[1].Reference.ToInt32(),
                                                marshalledParameters[2].Reference.ToInt32()));

                case 4:
                    return(Delphi.registerCall4(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32(),
                                                marshalledParameters[1].Reference.ToInt32(),
                                                marshalledParameters[2].Reference.ToInt32(),
                                                marshalledParameters[3].Reference.ToInt32()));

                case 5:
                    return(Delphi.registerCall5(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32(),
                                                marshalledParameters[1].Reference.ToInt32(),
                                                marshalledParameters[2].Reference.ToInt32(),
                                                marshalledParameters[3].Reference.ToInt32(),
                                                marshalledParameters[4].Reference.ToInt32()));

                case 6:
                    return(Delphi.registerCall6(_callTable[method],
                                                marshalledParameters[0].Reference.ToInt32(),
                                                marshalledParameters[1].Reference.ToInt32(),
                                                marshalledParameters[2].Reference.ToInt32(),
                                                marshalledParameters[3].Reference.ToInt32(),
                                                marshalledParameters[4].Reference.ToInt32(),
                                                marshalledParameters[5].Reference.ToInt32()));

                default:
                    throw new NotImplementedException($"No execution path to handle {parameters.Length} parameters.");
                }
            }
            finally
            {
                foreach (var param in marshalledParameters)
                {
                    param.Dispose();
                }
            }
        }
Exemplo n.º 7
0
        private Impersonation(string username, string domain, string password, LogonType logonType, BuiltinUser builtinUser)
        {
            switch (builtinUser)
            {
            case BuiltinUser.None:
                if (string.IsNullOrEmpty(username))
                {
                    return;
                }
                break;

            case BuiltinUser.LocalService:
                username = "******";
                break;

            case BuiltinUser.NetworkService:
                username = "******";
                break;
            }

            IntPtr userToken            = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = NativeMethod.LogonUser(username, domain, password, logonType, LogonProvider.Default, out userToken);

            if (loggedOn)
            {
                try
                {
                    // Create a duplication of the usertoken, this is a solution
                    // for the known bug that is published under KB article Q319615.
                    if (NativeMethod.DuplicateToken(userToken, 2, ref userTokenDuplication))
                    {
                        // Create windows identity from the token and impersonate the user.
                        WindowsIdentity identity = new WindowsIdentity(userTokenDuplication);
                        _impersonationContext = identity.Impersonate();
                    }
                    //else
                    //{
                    //    // Token duplication failed!
                    //    // Use the default ctor overload
                    //    // that will use Mashal.GetLastWin32Error();
                    //    // to create the exceptions details.
                    //    throw new Win32Exception();
                    //}
                }
                finally
                {
                    // Close usertoken handle duplication when created.
                    if (!userTokenDuplication.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        NativeMethod.CloseHandle(userTokenDuplication);
                        userTokenDuplication = IntPtr.Zero;
                    }

                    // Close usertoken handle when created.
                    if (!userToken.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        NativeMethod.CloseHandle(userToken);
                        userToken = IntPtr.Zero;
                    }
                }
            }
            //else
            //{
            //    // Logon failed!
            //    // Use the default ctor overload that
            //    // will use Mashal.GetLastWin32Error();
            //    // to create the exceptions details.
            //    throw new Win32Exception();
            //}
        }
Exemplo n.º 8
0
 public static bool RegisterTouchWindow(IntPtr hwnd)
 {
     return(NativeMethod.RegisterTouchWindow(hwnd, 0));
 }
Exemplo n.º 9
0
        public MethodInfo(ObjectModel objects, NativeInterface ni, NativeMethod method)
        {
            Name = method.Name;
            ResultType = new TypeInfo(objects, ni, method);

            var argNames = new List<NameInfo>();
            var argTypes = new List<ArgTypeInfo>();

            for (int i = 0; i < method.ArgNames.Length; ++i)
            {
                argNames.Add(new NameInfo(method.ArgNames[i]));
                argTypes.Add(new ArgTypeInfo(objects, method.ArgTypes[i]));

                if (argTypes[argTypes.Count - 1].ManagedOut.Length > 0)
                    HasOutArgs = true;
            }

            ArgNames = argNames.ToArray();
            ArgTypes = argTypes.ToArray();
        }
Exemplo n.º 10
0
        private void Form1_Load(object sender, EventArgs e)
        {
            int i = NativeMethod.SetWindowsHookEx(HookID.WH_KEYBOARD_LL, kbproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);

            Text = i.ToString();
        }
Exemplo n.º 11
0
    private void DoWriteCall(NativeMethod method, MethodInfo minfo)
    {
        string rtype = minfo.ResultType.Managed;

        if (rtype == "void")
            m_buffer.Append("			Unused.Value = ");
        else
            if (minfo.HasOutArgs)
                m_buffer.Append("			" + rtype + " result_ = ");
            else
                m_buffer.Append("			return ");

        if (rtype != "void")
        {
            m_buffer.Append("(");
            m_buffer.Append(rtype == "bool" ? "sbyte" : rtype);
            m_buffer.Append(") ");
        }

        if (m_interface.Category != null && !m_objects.EmittedType(m_interface.Name))
            if (method.IsClass)
                m_buffer.AppendFormat("{0}.Class.", m_interface.Name);
            else
                m_buffer.Append("_instance.");
        else if (method.IsClass)
            m_buffer.Append("ms_class.");

        m_buffer.Append("Call(\"");
        m_buffer.Append(method.Name);
        m_buffer.Append("\"");

        for (int i = 0; i < minfo.ArgNames.Length; ++i)
        {
            m_buffer.Append(", ");
            if (minfo.ArgTypes[i].Native == "SEL")
            {
                string aname = minfo.ArgNames[i].Managed;
                m_buffer.Append(aname + " != null ? new Selector(");
                m_buffer.Append(aname);
                m_buffer.Append(") : null");
            }
            else if (minfo.ArgTypes[i].ManagedOut.Length > 0)
            {
                m_buffer.Append(minfo.ArgNames[i].Managed);
                m_buffer.Append("Ptr");
            }
            else
                m_buffer.Append(minfo.ArgNames[i].Managed);
        }
        m_buffer.Append(")");
        if (minfo.ResultType.Managed == "bool")
        {
            m_buffer.Append(" != 0");
        }
        m_buffer.AppendLine(";");
    }
Exemplo n.º 12
0
        /// <summary>
        /// P/Invoke the native APIs related to named pipe operations to create
        /// the named pipe.
        /// </summary>
        public static void Run()
        {
            SafePipeHandle hNamedPipe = null;

            try
            {
                // Prepare the security attributes (the securityAttributes
                // parameter in CreateNamedPipe) for the pipe. This is optional.
                // If securityAttributes of CreateNamedPipe is null, the named
                // pipe gets a default security descriptor and the handle cannot
                // be inherited. The ACLs in the default security descriptor of a
                // pipe grant full control to the LocalSystem account, (elevated)
                // administrators, and the creator owner. They also give only
                // read access to members of the Everyone group and the anonymous
                // account. However, if you want to customize the security
                // permission of the pipe, (e.g. to allow Authenticated Users to
                // read from and write to the pipe), you need to create a
                // SECURITY_ATTRIBUTES object.
                SECURITY_ATTRIBUTES sa = null;
                sa = CreateNativePipeSecurity();

                // Create the named pipe.
                hNamedPipe = NativeMethod.CreateNamedPipe(
                    Program.FullPipeName,               // The unique pipe name.
                    PipeOpenMode.PIPE_ACCESS_DUPLEX,    // The pipe is duplex
                    PipeMode.PIPE_TYPE_MESSAGE |        // Message type pipe
                    PipeMode.PIPE_READMODE_MESSAGE |    // Message-read mode
                    PipeMode.PIPE_WAIT,                 // Blocking mode is on
                    PIPE_UNLIMITED_INSTANCES,           // Max server instances
                    Program.BufferSize,                 // Output buffer size
                    Program.BufferSize,                 // Input buffer size
                    NMPWAIT_USE_DEFAULT_WAIT,           // Time-out interval
                    sa                                  // Pipe security attributes
                    );

                if (hNamedPipe.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The named pipe ({0}) is created.",
                                  Program.FullPipeName);

                // Wait for the client to connect.
                Console.WriteLine("Waiting for the client's connection...");
                if (!NativeMethod.ConnectNamedPipe(hNamedPipe, IntPtr.Zero))
                {
                    if (Marshal.GetLastWin32Error() != ERROR_PIPE_CONNECTED)
                    {
                        throw new Win32Exception();
                    }
                }
                Console.WriteLine("Client is connected.");

                //
                // Receive a request from client.
                //

                string message;
                bool   finishRead = false;
                do
                {
                    byte[] bRequest = new byte[Program.BufferSize];
                    int    cbRequest = bRequest.Length, cbRead;

                    finishRead = NativeMethod.ReadFile(
                        hNamedPipe,             // Handle of the pipe
                        bRequest,               // Buffer to receive data
                        cbRequest,              // Size of buffer in bytes
                        out cbRead,             // Number of bytes read
                        IntPtr.Zero             // Not overlapped
                        );

                    if (!finishRead &&
                        Marshal.GetLastWin32Error() != ERROR_MORE_DATA)
                    {
                        throw new Win32Exception();
                    }

                    // Unicode-encode the received byte array and trim all the
                    // '\0' characters at the end.
                    message = Encoding.Unicode.GetString(bRequest).TrimEnd('\0');
                    Console.WriteLine("Receive {0} bytes from client: \"{1}\"",
                                      cbRead, message);
                }while (!finishRead);  // Repeat loop if ERROR_MORE_DATA

                //
                // Send a response from server to client.
                //

                message = Program.ResponseMessage;
                byte[] bResponse = Encoding.Unicode.GetBytes(message);
                int    cbResponse = bResponse.Length, cbWritten;

                if (!NativeMethod.WriteFile(
                        hNamedPipe,             // Handle of the pipe
                        bResponse,              // Message to be written
                        cbResponse,             // Number of bytes to write
                        out cbWritten,          // Number of bytes written
                        IntPtr.Zero             // Not overlapped
                        ))
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("Send {0} bytes to client: \"{1}\"",
                                  cbWritten, message.TrimEnd('\0'));

                // Flush the pipe to allow the client to read the pipe's contents
                // before disconnecting. Then disconnect the client's connection.
                NativeMethod.FlushFileBuffers(hNamedPipe);
                NativeMethod.DisconnectNamedPipe(hNamedPipe);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hNamedPipe != null)
                {
                    hNamedPipe.Close();
                    hNamedPipe = null;
                }
            }
        }
Exemplo n.º 13
0
    private bool DoTryFastCall(NativeMethod method, MethodInfo minfo)
    {
        if (!minfo.HasOutArgs)
        {
            if (minfo.ArgNames.Length == 0)
                return DoTryFastCall0(method, minfo);

            else if (minfo.ArgNames.Length == 1)
                return DoTryFastCall1(method, minfo);

            else if (minfo.ArgNames.Length == 2)
                return DoTryFastCall2(method, minfo);
        }

        return false;
    }
Exemplo n.º 14
0
    private bool DoTryFastCall2(NativeMethod method, MethodInfo minfo)
    {
        bool done = false;

        string rtype = minfo.ResultType.Managed;
        string rlabel, a0label, a1label;

        string rkey = DoGetKey(minfo.ResultType);
        string a0key = DoGetKey(minfo.ArgTypes[0]);
        string a1key = DoGetKey(minfo.ArgTypes[1]);

        if (m_labels.TryGetValue(rkey, out rlabel) && m_labels.TryGetValue(a0key, out a0label) && m_labels.TryGetValue(a1key, out a1label))
        {
            string thisPtr;
            if (m_interface.Category != null && !m_objects.EmittedType(m_interface.Name))
                if (method.IsClass)
                    thisPtr = string.Format("{0}.Class", m_interface.Name);
                else
                    thisPtr = "_instance";
            else if (method.IsClass)
                thisPtr = "ms_class";
            else
                thisPtr = "this";

            m_buffer.AppendLine("			IntPtr exception_ = IntPtr.Zero;");
            DoAppendFastArgProlog(minfo, 0);
            DoAppendFastArgProlog(minfo, 1);

            m_buffer.Append("			");
            if (rkey != "void")
                m_buffer.AppendFormat("{0} result_ = ", m_dtypes[rkey]);
            m_buffer.AppendFormat("DirectCalls.Call{0}{1}{2}({3}, new Selector(\"{4}\"), ", rlabel, a0label, a1label, thisPtr, method.Name);
            DoAppendFastArg(minfo, 0);
            DoAppendFastArg(minfo, 1);
            m_buffer.AppendLine("ref exception_);");

            DoAppendFastArgEpilog(minfo, 0);
            DoAppendFastArgEpilog(minfo, 1);
            m_buffer.AppendLine("			if (exception_ != IntPtr.Zero)");
            m_buffer.AppendLine("				CocoaException.Raise(exception_);");
            DoAppendFastResult(rkey, rtype, minfo);

            done = true;
        }

        return done;
    }
Exemplo n.º 15
0
    private string DoGetMethodSuffix(NativeMethod method)
    {
        string suffix = string.Empty;

        if (m_objects.EmittedType(m_interface.Name))
        {
            NativeInterface ri = m_objects.FindInterface(m_interface.Name);

            List<NativeMethod> methods;
            if (m_objects.TryGetMethods(ri, out methods))
            {
                if (method.IsClass)
                {
                    if (DoBaseHasMethod(ri.Name, method.Name, false))
                        suffix = "_c";
                }
                else
                {
                    if (DoBaseHasMethod(ri.BaseName, method.Name, true))	// only use _i if the base class has a static method of the same name
                        suffix = "_i";
                }
            }
        }

        return suffix;
    }
Exemplo n.º 16
0
    private bool DoGenerateMethod(NativeMethod nm, bool writeBlank, NativeProtocol protocol)
    {
        bool wrote = false;

        bool defined = false;
        if (protocol != null)
        {
            defined = DoPriorProtocolHasMethod(protocol, nm.Name, nm.IsClass);

            if (!defined)
                defined = DoInterfaceHasMethod(nm.Name, nm.IsClass);

            if (!defined)
                defined = DoBaseHasMethod(m_interface.BaseName, nm.Name, nm.IsClass);
        }
        else if (m_interface.Category != null)
        {
            if (m_objects.EmittedType(m_interface.Name))
            {
                defined = DoInterfaceHasMethod(nm.Name, nm.IsClass);

                if (!defined)
                {
                    NativeInterface ri = m_objects.FindInterface(m_interface.Name);
                    defined = DoBaseHasMethod(ri.BaseName, nm.Name, nm.IsClass);
                }
            }
        }
        else
        {
            defined = DoBaseHasMethod(m_interface.BaseName, nm.Name, nm.IsClass);
        }

        if (!defined)
        {
            Blacklist black = m_blacklist.SingleOrDefault(b => b.Interface == m_interface.Name && b.Method == nm.Name);
            if (black == null)
            {
                if (nm.ArgTypes.Length > 0 && nm.ArgTypes[nm.ArgTypes.Length - 1] == "...")
                {
                    DoWrite("		// skipping variadic {0}", nm.Name);
                    Console.Error.WriteLine("Ignoring {0}::{1} (it's variadic)", m_interface.Name, nm.Name);
                }
                else if (nm.ArgTypes.Length > 0 && nm.ArgTypes.Any(t => t.Contains("( * )")))
                {
                    DoWrite("		// skipping function pointer {0}", nm.Name);
                    Console.Error.WriteLine("Ignoring {0}::{1} (it uses a function pointer)", m_interface.Name, nm.Name);
                }
                else if (nm.ArgTypes.Length > 0 && (nm.ArgTypes.Any(t => t.Contains("( ^ )")) || nm.ArgTypes.Any(t => t.Contains("(^)"))))
                {
                    DoWrite("		// skipping block {0}", nm.Name);
                    Console.Error.WriteLine("Ignoring {0}::{1} (it uses a block)", m_interface.Name, nm.Name);
                }
                else if (nm.ReturnType.Contains("( ^ )") || nm.ReturnType.Contains("(^)"))
                {
                    DoWrite("		// skipping block {0}", nm.Name);
                    Console.Error.WriteLine("Ignoring {0}::{1} (it uses a block)", m_interface.Name, nm.Name);
                }
                else
                {
                    if (writeBlank)
                        DoWrite("\t\t");

                    DoWrite("	\t/// <exclude/>");
                    DoWriteMethod(nm);
                    wrote = true;
                }
            }
            else
            {
                DoWrite("		// skipping {0} {1}", black.Method, black.Reason);
            }
        }
        else
            DoWrite("		// skipping {0} (it's already defined)", nm.Name);

        return wrote;
    }
Exemplo n.º 17
0
        public TypeInfo(ObjectModel objects, NativeInterface ni, NativeMethod method)
        {
            Native = method.ReturnType;

            string type = objects.MapResult(ni.Name, method.Name, method.ReturnType);
            Managed = MapType(objects, type);
            if (Managed == "IBAction")
                Managed = "void";
        }
Exemplo n.º 18
0
 /// <summary>
 /// 実行関数
 /// </summary>
 /// <returns></returns>
 public int Execute()
 {
     _ope_info.fFlags = _ope_detail.FlagsToBit();
     return(NativeMethod.SHFileOperation(ref _ope_info));
 }
Exemplo n.º 19
0
 protected override sealed void OnDispose()
 {
     NativeMethod.UnhookWindowsHookEx(hook);
     AfterDispose();
 }
Exemplo n.º 20
0
 public void RedefineMethodAsObjectValue()
 {
     DefinedClass klass = new DefinedClass("Spam");
     IFunction function = new NativeMethod(GetValueMethod);
     klass.SetMethod("foo", function);
     DynamicObject dynobj = new DynamicObject(klass);
     dynobj.SetValue("foo", 1);
     Assert.AreEqual(1, dynobj.GetValue("foo"));
 }
 public void TestNullTypeAction()
 {
     var method = new NativeMethod(null, (_, __) => { });
 }
Exemplo n.º 22
0
        public void InvokeMethodThatReturnsSelf()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction function = new NativeMethod(SelfMethod);
            klass.SetMethod("foo", function);
            DynamicObject dynobj = new DynamicObject(klass);

            var result = dynobj.Invoke("foo", null, null, null);

            Assert.IsNotNull(result);
            Assert.AreEqual(dynobj, result);
        }
 public void TestNullAction()
 {
     var method = new NativeMethod("foo", default(Action <InvokeCallback, JArray>));
 }
Exemplo n.º 24
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public static IntPtr GetForegroundWindowHandle()
 {
     return(NativeMethod.GetForegroundWindow());
 }
Exemplo n.º 25
0
    private void DoWriteMethod(NativeMethod method)
    {
        MethodInfo minfo = new MethodInfo(m_objects, m_interface, method);

        // pure attribute
        string name = DoGetMethodName(method.Name, DoGetMethodSuffix(method));
        if (PureMethods.IsPure(name))
            m_buffer.AppendLine("		[Pure]");

        // obsolete attribute
        if (method.Obsolete != null)
        {
            m_buffer.Append("		[Obsolete(\"");
            m_buffer.Append(method.Obsolete);
            m_buffer.AppendLine("\")]");
        }

        // signature
        m_buffer.Append("		public ");
        if (method.IsClass || (m_interface.Category != null && !m_objects.EmittedType(m_interface.Name)))
            m_buffer.Append("static ");

        m_buffer.Append(minfo.ResultType.Managed);
        m_buffer.Append(" ");
        m_buffer.Append(name);
        m_buffer.Append("(");
        if (m_interface.Category != null && !m_objects.EmittedType(m_interface.Name) && !method.IsClass)
        {
            m_buffer.AppendFormat("this {0} _instance", m_interface.Name);
            if (method.ArgNames.Length > 0)
                m_buffer.Append(", ");
        }
        for (int i = 0; i < minfo.ArgNames.Length; ++i)
        {
            m_buffer.Append(minfo.ArgTypes[i].Managed);
            m_buffer.Append(" ");
            m_buffer.Append(minfo.ArgNames[i].Managed);

            if (i + 1 < minfo.ArgNames.Length)
                m_buffer.Append(", ");
        }
        m_buffer.AppendLine(")");

        DoWrite("		{");

        // body
        DoWriteProlog(minfo);
        if (DoTryFastCall(method, minfo))
        {
            ++m_fastCalls;
        }
        else
        {
            ++m_slowCalls;
            DoWriteCall(method, minfo);
        }
        DoWriteEpilog(minfo);

        // trailer
        DoWrite("		}");
    }
 /// <summary>
 /// A public method with two outputs: the current process Id and the
 /// current thread Id.
 /// </summary>
 /// <param name="processId">[out] The current process Id</param>
 /// <param name="threadId">[out] The current thread Id</param>
 public void GetProcessThreadID(out uint processId, out uint threadId)
 {
     processId = NativeMethod.GetCurrentProcessId();
     threadId  = NativeMethod.GetCurrentThreadId();
 }
Exemplo n.º 27
0
 protected override bool ReleaseHandle()
 {
     return(NativeMethod.DwmUnregisterThumbnail(this.handle) == 0);
 }
 public void TestNullTypeFunc()
 {
     var method = new NativeMethod(null, (_, __) => default(JToken));
 }
Exemplo n.º 29
0
 public static UInt32 SetLong(IntPtr hWnd, GWL index, UInt32 newLong)
 {
     return(NativeMethod.SetWindowLong(hWnd, index, newLong));
 }
 public void TestNullFunc()
 {
     var method = new NativeMethod("foo", default(Func <InvokeCallback, JArray, JToken>));
 }
Exemplo n.º 31
0
 public static UInt32 GetLong(IntPtr hWnd, GWL index)
 {
     return(NativeMethod.GetWindowLong(hWnd, index));
 }
Exemplo n.º 32
0
 public void InitializeTouch()
 {
     NativeMethod.InitializeTouchInjection(10, TouchFeedback.None);
     this._initialized = true;
 }
        /// <summary>获取注册表项权限</summary>
        /// <remarks>将注册表项所有者改为当前管理员用户</remarks>
        /// <param name="regPath">要获取权限的注册表完整路径</param>
        public static void TakeRegKeyOwnerShip(string regPath)
        {
            if (regPath.IsNullOrWhiteSpace())
            {
                return;
            }
            RegistryKey     key = null;
            WindowsIdentity id  = null;

            //利用试错判断是否有写入权限
            try { key = RegistryEx.GetRegistryKey(regPath, true); }
            catch
            {
                try
                {
                    //获取当前用户的ID
                    id = WindowsIdentity.GetCurrent();

                    //添加TakeOwnership特权
                    bool flag = NativeMethod.TrySetPrivilege(NativeMethod.TakeOwnership, true);
                    if (!flag)
                    {
                        throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership);
                    }

                    //添加恢复特权(必须这样做才能更改所有者)
                    flag = NativeMethod.TrySetPrivilege(NativeMethod.Restore, true);
                    if (!flag)
                    {
                        throw new PrivilegeNotHeldException(NativeMethod.Restore);
                    }

                    //打开没有权限的注册表路径
                    key = RegistryEx.GetRegistryKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);

                    RegistrySecurity security = key.GetAccessControl(AccessControlSections.All);

                    //得到真正所有者
                    //IdentityReference oldId = security.GetOwner(typeof(SecurityIdentifier));
                    //SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());

                    //使进程用户成为所有者
                    security.SetOwner(id.User);
                    key.SetAccessControl(security);

                    //添加完全控制
                    RegistryAccessRule fullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl,
                                                                           InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    security.AddAccessRule(fullAccess);
                    key.SetAccessControl(security);

                    //注册表操作(写入、删除)
                    //key.SetValue("temp", "");//示例

                    //恢复原有所有者
                    //security.SetOwner(siTrustedInstaller);
                    //key.SetAccessControl(security);

                    //收回原有权利
                    //security.RemoveAccessRule(fullAccess);
                    //key.SetAccessControl(security);

                    ///得到真正所有者、注册表操作、恢复原有所有者、收回原有权利,这四部分在原文中没有被注释掉
                    ///但是如果保留这四部分,会在恢复原有所有者这一步抛出异常,提示没有权限,
                    ///不过我发现经过上面的操作,虽然无法还原所有者权限,但是已经获取了注册表权限
                    ///即已经将TrustedInstaller权限更改为当前管理员用户权限,我要的目的已经达到了
                }
                catch { }
            }
            finally { key?.Close(); id?.Dispose(); }
        }
Exemplo n.º 34
0
 private static void KillTimerProc(object stateInfo)
 {
     NativeMethod.PostThreadMessage((stateInfo as SingleComServer)._nMainThreadID,
                                    NativeMethod.WM_QUIT, UIntPtr.Zero, IntPtr.Zero);
 }
        /// <summary>
        /// P/Invoke the native APIs related to named pipe operations to connect
        /// to the named pipe.
        /// </summary>
        public static void Run()
        {
            SafePipeHandle hNamedPipe = null;

            try
            {
                // Try to open the named pipe identified by the pipe name.
                while (true)
                {
                    hNamedPipe = NativeMethod.CreateFile(
                        Program.FullPipeName,                   // Pipe name
                        FileDesiredAccess.GENERIC_READ |        // Read access
                        FileDesiredAccess.GENERIC_WRITE,        // Write access
                        FileShareMode.Zero,                     // No sharing
                        null,                                   // Default security attributes
                        FileCreationDisposition.OPEN_EXISTING,  // Opens existing pipe
                        0,                                      // Default attributes
                        IntPtr.Zero                             // No template file
                        );

                    // If the pipe handle is opened successfully ...
                    if (!hNamedPipe.IsInvalid)
                    {
                        Console.WriteLine("The named pipe ({0}) is connected.",
                                          Program.FullPipeName);
                        break;
                    }

                    // Exit if an error other than ERROR_PIPE_BUSY occurs.
                    if (Marshal.GetLastWin32Error() != ERROR_PIPE_BUSY)
                    {
                        throw new Win32Exception();
                    }

                    // All pipe instances are busy, so wait for 5 seconds.
                    if (!NativeMethod.WaitNamedPipe(Program.FullPipeName, 5000))
                    {
                        throw new Win32Exception();
                    }
                }

                // Set the read mode and the blocking mode of the named pipe. In
                // this sample, we set data to be read from the pipe as a stream
                // of messages.
                PipeMode mode = PipeMode.PIPE_READMODE_MESSAGE;
                if (!NativeMethod.SetNamedPipeHandleState(hNamedPipe, ref mode,
                                                          IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Win32Exception();
                }

                //
                // Send a request from client to server.
                //

                string message = Program.RequestMessage;
                byte[] bRequest = Encoding.Unicode.GetBytes(message);
                int    cbRequest = bRequest.Length, cbWritten;

                if (!NativeMethod.WriteFile(
                        hNamedPipe,             // Handle of the pipe
                        bRequest,               // Message to be written
                        cbRequest,              // Number of bytes to write
                        out cbWritten,          // Number of bytes written
                        IntPtr.Zero             // Not overlapped
                        ))
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("Send {0} bytes to server: \"{1}\"",
                                  cbWritten, message.TrimEnd('\0'));

                //
                // Receive a response from server.
                //

                bool finishRead = false;
                do
                {
                    byte[] bResponse = new byte[Program.BufferSize];
                    int    cbResponse = bResponse.Length, cbRead;

                    finishRead = NativeMethod.ReadFile(
                        hNamedPipe,             // Handle of the pipe
                        bResponse,              // Buffer to receive data
                        cbResponse,             // Size of buffer in bytes
                        out cbRead,             // Number of bytes read
                        IntPtr.Zero             // Not overlapped
                        );

                    if (!finishRead &&
                        Marshal.GetLastWin32Error() != ERROR_MORE_DATA)
                    {
                        throw new Win32Exception();
                    }

                    // Unicode-encode the received byte array and trim all the
                    // '\0' characters at the end.
                    message = Encoding.Unicode.GetString(bResponse).TrimEnd('\0');
                    Console.WriteLine("Receive {0} bytes from server: \"{1}\"",
                                      cbRead, message);
                }while (!finishRead);  // Repeat loop if ERROR_MORE_DATA
            }
            catch (Exception ex)
            {
                Console.WriteLine("The client throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hNamedPipe != null)
                {
                    hNamedPipe.Close();
                    hNamedPipe = null;
                }
            }
        }
Exemplo n.º 36
0
 public void Add(NativeMethod method)
 {
     m_methods.Add(method);
 }
Exemplo n.º 37
0
 /// <summary>
 /// Release handle
 /// </summary>
 protected override bool ReleaseHandle()
 {
     return(NativeMethod.FreeLibrary(handle));
 }
Exemplo n.º 38
0
        static void Main(string[] args)
        {
            SafeMailslotHandle hMailslot = null;

            try
            {
                // Prepare the security attributes (the lpSecurityAttributes parameter
                // in CreateMailslot) for the mailslot. This is optional. If the
                // lpSecurityAttributes parameter of CreateMailslot is NULL, the
                // mailslot gets a default security descriptor and the handle cannot
                // be inherited. The ACLs in the default security descriptor of a
                // mailslot grant full control to the LocalSystem account, (elevated)
                // administrators, and the creator owner. They also give only read
                // access to members of the Everyone group and the anonymous account.
                // However, if you want to customize the security permission of the
                // mailslot, (e.g. to allow Authenticated Users to read from and
                // write to the mailslot), you need to create a SECURITY_ATTRIBUTES
                // structure.
                SECURITY_ATTRIBUTES sa = null;
                sa = CreateMailslotSecurity();

                // Create the mailslot.
                hMailslot = NativeMethod.CreateMailslot(
                    MailslotName,               // The name of the mailslot
                    0,                          // No maximum message size
                    MAILSLOT_WAIT_FOREVER,      // Waits forever for a message
                    sa                          // Mailslot security attributes
                    );

                if (hMailslot.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The mailslot ({0}) is created.", MailslotName);

                // Check messages in the mailslot.
                Console.Write("Press ENTER to check new messages or press Q to quit ...");
                string cmd = Console.ReadLine();
                while (!cmd.Equals("Q", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Checking new messages...");
                    ReadMailslot(hMailslot);

                    Console.Write("Press ENTER to check new messages or press Q to quit ...");
                    cmd = Console.ReadLine();
                }
            }
            catch (Win32Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMailslot != null)
                {
                    hMailslot.Close();
                    hMailslot = null;
                }
            }
        }
Exemplo n.º 39
0
    // Method := ('-' / '+') S ParensType? (Parameter+ VarArgs? / Identifier) Deprecated? Availability? ';' S;
    //
    // Parameter := Identifier? ':' S ParensType? Identifier;
    //
    // VarArgs := ',' S '...' S ('NS_REQUIRES_NIL_TERMINATION' S)?;
    //
    // ParensType := '(' S Type ')' S;
    private NativeMethod DoAnalyzeMethod(XmlNode node, string deprecated)
    {
        deprecated = deprecated ?? DoFindDeprecated(node);

        var name = new System.Text.StringBuilder();
        string rtype = node.ChildNodes[1].Name == "ParensType" ? node.ChildNodes[1].InnerText : "id";
        var argNames = new List<string>();
        var argTypes = new List<string>();

        XmlNode identifier = DoFind(node, "Identifier");
        if (identifier != null)
        {
            name.Append(identifier.InnerText);
        }
        else
        {
            for (int i = 1; i < node.ChildNodes.Count; ++i)
            {
                XmlNode p = node.ChildNodes[i];
                if (p.Name == "Parameter")
                {
                    if (p.ChildNodes[0].Name == "Identifier")
                        name.Append(p.ChildNodes[0].InnerText);
                    name.Append(':');

                    XmlNode parens = DoFind(p, "ParensType");
                    XmlNode aname = DoFindLast(p, "Identifier");
                    if (parens != null)
                        argTypes.Add(parens.InnerText);
                    else
                        argTypes.Add("id");
                    if (argNames.Contains(aname.InnerText))
                        argNames.Add(aname.InnerText + "2");		// clientAcceptedChangesForRecordWithIdentifier:formattedRecord:newRecordIdentifier: has duplicate argument names...
                    else
                        argNames.Add(aname.InnerText);
                }
            }

            XmlNode varArgs = DoFind(node, "VarArgs");
            if (varArgs != null)
            {
                argNames.Add(string.Empty);
                argTypes.Add("...");
            }
        }

        var result = new NativeMethod{
            IsClass = node.ChildNodes[0].Value == "+",
            Name = name.ToString(),
            ReturnType = rtype,
            ArgNames = argNames.ToArray(),
            ArgTypes = argTypes.ToArray(),
            Obsolete = deprecated};

        return result;
    }
Exemplo n.º 40
0
        public void RaiseWhenThereIsAValueInsteadOfAMethod()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction function = new NativeMethod(GetValueMethod);
            klass.SetMethod("foo", function);
            DynamicObject dynobj = new DynamicObject(klass);
            dynobj.SetValue("foo", 1);

            try
            {
                dynobj.Invoke("foo", null, new object[] { "one" }, null);
                Assert.Fail("Exception expected");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(TypeError));
                Assert.AreEqual("'int' object is not callable", ex.Message);
            }
        }
Exemplo n.º 41
0
        /// <summary>
        /// The function gets the integrity level of the current process. Integrity
        /// level is only available on Windows Vista and newer operating systems, thus
        /// GetProcessIntegrityLevel throws a C++ exception if it is called on systems
        /// prior to Windows Vista.
        /// </summary>
        /// <returns>
        /// Returns the integrity level of the current process. It is usually one of
        /// these values:
        ///
        ///    SECURITY_MANDATORY_UNTRUSTED_RID - means untrusted level. It is used
        ///    by processes started by the Anonymous group. Blocks most write access.
        ///    (SID: S-1-16-0x0)
        ///
        ///    SECURITY_MANDATORY_LOW_RID - means low integrity level. It is used by
        ///    Protected Mode Internet Explorer. Blocks write acess to most objects
        ///    (such as files and registry keys) on the system. (SID: S-1-16-0x1000)
        ///
        ///    SECURITY_MANDATORY_MEDIUM_RID - means medium integrity level. It is
        ///    used by normal applications being launched while UAC is enabled.
        ///    (SID: S-1-16-0x2000)
        ///
        ///    SECURITY_MANDATORY_HIGH_RID - means high integrity level. It is used
        ///    by administrative applications launched through elevation when UAC is
        ///    enabled, or normal applications if UAC is disabled and the user is an
        ///    administrator. (SID: S-1-16-0x3000)
        ///
        ///    SECURITY_MANDATORY_SYSTEM_RID - means system integrity level. It is
        ///    used by services and other system-level applications (such as Wininit,
        ///    Winlogon, Smss, etc.)  (SID: S-1-16-0x4000)
        ///
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception
        /// with the last error code.
        /// </exception>
        public static int GetProcessIntegrityLevel()
        {
            int             IL        = -1;
            SafeTokenHandle hToken    = null;
            int             cbTokenIL = 0;
            IntPtr          pTokenIL  = IntPtr.Zero;

            try
            {
                // Open the access token of the current process with TOKEN_QUERY.
                if (!NativeMethod.OpenProcessToken(Process.GetCurrentProcess().Handle,
                                                   NativeMethod.TOKEN_QUERY, out hToken))
                {
                    throw new Win32Exception();
                }

                // Then we must query the size of the integrity level information
                // associated with the token. Note that we expect GetTokenInformation
                // to return false with the ERROR_INSUFFICIENT_BUFFER error code
                // because we've given it a null buffer. On exit cbTokenIL will tell
                // the size of the group information.
                if (!NativeMethod.GetTokenInformation(hToken,
                                                      TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0,
                                                      out cbTokenIL))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error != NativeMethod.ERROR_INSUFFICIENT_BUFFER)
                    {
                        // When the process is run on operating systems prior to
                        // Windows Vista, GetTokenInformation returns false with the
                        // ERROR_INVALID_PARAMETER error code because
                        // TokenIntegrityLevel is not supported on those OS's.
                        throw new Win32Exception(error);
                    }
                }

                // Now we allocate a buffer for the integrity level information.
                pTokenIL = Marshal.AllocHGlobal(cbTokenIL);
                if (pTokenIL == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // Now we ask for the integrity level information again. This may fail
                // if an administrator has added this account to an additional group
                // between our first call to GetTokenInformation and this one.
                if (!NativeMethod.GetTokenInformation(hToken,
                                                      TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenIL, cbTokenIL,
                                                      out cbTokenIL))
                {
                    throw new Win32Exception();
                }

                // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object.
                TOKEN_MANDATORY_LABEL tokenIL = (TOKEN_MANDATORY_LABEL)
                                                Marshal.PtrToStructure(pTokenIL, typeof(TOKEN_MANDATORY_LABEL));

                // Integrity Level SIDs are in the form of S-1-16-0xXXXX. (e.g.
                // S-1-16-0x1000 stands for low integrity level SID). There is one
                // and only one subauthority.
                IntPtr pIL = NativeMethod.GetSidSubAuthority(tokenIL.Label.Sid, 0);
                IL = Marshal.ReadInt32(pIL);
            }
            finally
            {
                // Centralized cleanup for all allocated resources.
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (pTokenIL != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pTokenIL);
                    pTokenIL  = IntPtr.Zero;
                    cbTokenIL = 0;
                }
            }

            return(IL);
        }
Exemplo n.º 42
0
        /// <summary>
        /// The function launches an application at low integrity level.
        /// </summary>
        /// <param name="commandLine">
        /// The command line to be executed. The maximum length of this string is 32K
        /// characters.
        /// </param>
        /// <param name="selectedIntegrityLevel">
        /// Numeric representation of integrity level with which process has to be started
        /// </param>
        /// <remarks>
        /// To start a low-integrity process,
        /// 1) Duplicate the handle of the current process, which is at medium
        ///    integrity level.
        /// 2) Use SetTokenInformation to set the integrity level in the access token
        ///    to Low.
        /// 3) Use CreateProcessAsUser to create a new process using the handle to
        ///    the low integrity access token.
        /// </remarks>
        public static void CreateSpecificIntegrityProcess(string commandLine, int selectedIntegrityLevel)
        {
            SafeTokenHandle     hToken        = null;
            SafeTokenHandle     hNewToken     = null;
            IntPtr              pIntegritySid = IntPtr.Zero;
            int                 cbTokenInfo   = 0;
            IntPtr              pTokenInfo    = IntPtr.Zero;
            STARTUPINFO         si            = new STARTUPINFO();
            PROCESS_INFORMATION pi            = new PROCESS_INFORMATION();

            try
            {
                // Open the primary access token of the process.
                if (!NativeMethod.OpenProcessToken(Process.GetCurrentProcess().Handle,
                                                   NativeMethod.TOKEN_DUPLICATE | NativeMethod.TOKEN_ADJUST_DEFAULT |
                                                   NativeMethod.TOKEN_QUERY | NativeMethod.TOKEN_ASSIGN_PRIMARY,
                                                   out hToken))
                {
                    throw new Win32Exception();
                }

                // Duplicate the primary token of the current process.
                if (!NativeMethod.DuplicateTokenEx(hToken, 0, IntPtr.Zero,
                                                   SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                                                   TOKEN_TYPE.TokenPrimary, out hNewToken))
                {
                    throw new Win32Exception();
                }

                // Create the low integrity SID.
                if (!NativeMethod.AllocateAndInitializeSid(
                        ref NativeMethod.SECURITY_MANDATORY_LABEL_AUTHORITY, 1,
                        selectedIntegrityLevel,
                        0, 0, 0, 0, 0, 0, 0, out pIntegritySid))
                {
                    throw new Win32Exception();
                }

                TOKEN_MANDATORY_LABEL tml;
                tml.Label.Attributes = NativeMethod.SE_GROUP_INTEGRITY;
                tml.Label.Sid        = pIntegritySid;

                // Marshal the TOKEN_MANDATORY_LABEL struct to the native memory.
                cbTokenInfo = Marshal.SizeOf(tml);
                pTokenInfo  = Marshal.AllocHGlobal(cbTokenInfo);
                Marshal.StructureToPtr(tml, pTokenInfo, false);

                // Set the integrity level in the access token to low.
                if (!NativeMethod.SetTokenInformation(hNewToken,
                                                      TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenInfo,
                                                      cbTokenInfo + NativeMethod.GetLengthSid(pIntegritySid)))
                {
                    throw new Win32Exception();
                }

                // Create the new process at the Low integrity level.
                si.cb = Marshal.SizeOf(si);
                if (!NativeMethod.CreateProcessAsUser(hNewToken, null, commandLine,
                                                      IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref si,
                                                      out pi))
                {
                    throw new Win32Exception();
                }
            }
            finally
            {
                // Centralized cleanup for all allocated resources.
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (hNewToken != null)
                {
                    hNewToken.Close();
                    hNewToken = null;
                }
                if (pIntegritySid != IntPtr.Zero)
                {
                    NativeMethod.FreeSid(pIntegritySid);
                    pIntegritySid = IntPtr.Zero;
                }
                if (pTokenInfo != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pTokenInfo);
                    pTokenInfo  = IntPtr.Zero;
                    cbTokenInfo = 0;
                }
                if (pi.hProcess != IntPtr.Zero)
                {
                    NativeMethod.CloseHandle(pi.hProcess);
                    pi.hProcess = IntPtr.Zero;
                }
                if (pi.hThread != IntPtr.Zero)
                {
                    NativeMethod.CloseHandle(pi.hThread);
                    pi.hThread = IntPtr.Zero;
                }
            }
        }
Exemplo n.º 43
0
 /// <summary> Send Message </summary>
 /// <param name="hWnd">Target Handle</param>
 /// <param name="uiMsg">Send Message</param>
 /// <param name="wParam">wParam</param>
 /// <param name="lParam">lParam</param>
 /// <returns></returns>
 public static Int64 Send(IntPtr hWnd, UInt32 uiMsg, IntPtr wParam, IntPtr lParam)
 {
     return(NativeMethod.SendMessage(hWnd, uiMsg, wParam, lParam));
 }
Exemplo n.º 44
0
        public void InvokeMethodDefinedInClass()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction function = new NativeMethod(DummyMethod);
            klass.SetMethod("foo", function);
            DynamicObject dynobj = new DynamicObject(klass);

            var result = dynobj.Invoke("foo", null, null, null);

            Assert.IsNull(result);
        }
Exemplo n.º 45
0
 /// <summary> Post Message </summary>
 /// <param name="hWnd">Target Handle</param>
 /// <param name="uiMsg">Send Message</param>
 /// <param name="wParam">wParam</param>
 /// <param name="lParam">lParam</param>
 /// <returns></returns>
 public static Int64 Post(IntPtr hWnd, UInt32 uiMsg, UInt32 wParam, UInt32 lParam)
 {
     return(NativeMethod.PostMessage(hWnd, uiMsg, wParam, lParam));
 }
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            SafeFileMappingHandle hMapFile = null;
            IntPtr pView = IntPtr.Zero;

            try
            {
                // Try to open the named file mapping.
                hMapFile = NativeMethod.OpenFileMapping(
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    false,                          // Do not inherit the name
                    FullMapName                     // File mapping name
                    );

                if (hMapFile.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file mapping ({0}) is opened", FullMapName);

                // Map a view of the file mapping into the address space of the
                // current process.
                pView = NativeMethod.MapViewOfFile(
                    hMapFile,                       // Handle of the map object
                    FileMapAccess.FILE_MAP_READ,    // Read access
                    0,                              // High-order DWORD of file offset
                    ViewOffset,                     // Low-order DWORD of file offset
                    ViewSize                        // Byte# to map to view
                    );

                if (pView == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The file view is mapped");

                // Read and display the content in the view.
                string message = Marshal.PtrToStringUni(pView);
                Console.WriteLine("Read from the file mapping:\n\"{0}\"", message);

                // Wait to clean up resources and stop the process.
                Console.Write("Press ENTER to clean up resources and quit");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The process throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMapFile != null)
                {
                    if (pView != IntPtr.Zero)
                    {
                        // Unmap the file view.
                        NativeMethod.UnmapViewOfFile(pView);
                        pView = IntPtr.Zero;
                    }
                    // Close the file mapping object.
                    hMapFile.Close();
                    hMapFile = null;
                }
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// P/Invoke native APIs related to named pipe operations to create the named pipe.
        /// System.IO.Pipes in Unity is missing crucial types/methods for performing reliable and
        /// accurate transfers. Such as bytesSents/bytesReceived.
        /// </summary>
        public static void Run()
        {
            while (!KillServerRequested)
            {
                // ----------------------------------------------------------------------------------------------------------------
                // Create the named pipe.
                using (SafePipeHandle hNamedPipe = NativeMethod.CreateNamedPipe(
                           IPCServer.FullPipeName,          // The unique pipe name.
                           PipeOpenMode.PIPE_ACCESS_DUPLEX, // The pipe is duplex
                           PipeMode.PIPE_TYPE_MESSAGE |     // Message type pipe
                           PipeMode.PIPE_READMODE_MESSAGE | // Message-read mode
                           PipeMode.PIPE_WAIT,              // Blocking mode is on
                           2,                               // Max server instances
                           IPCServer.BufferSize,            // Output buffer size
                           IPCServer.BufferSize,            // Input buffer size
                           NMPWAIT_USE_DEFAULT_WAIT         // Time-out interval
                           ))
                {
                    try
                    {
                        if (hNamedPipe.IsInvalid)
                        {
                            throw new Win32Exception();
                        }

                        pipeHandle = hNamedPipe;
                        Console.WriteLine("[IPC Server Waiting for Connection] - \"{0}\"", IPCServer.FullPipeName);

                        // ----------------------------------------------------------------------------------------------------------------
                        // Wait for the connections. Runs on background thread.
                        if (!NativeMethod.ConnectNamedPipe(hNamedPipe, IntPtr.Zero))
                        {
                            if (Marshal.GetLastWin32Error() != ERROR_PIPE_CONNECTED)
                            {
                                throw new Win32Exception();
                            }
                        }
                        Console.WriteLine("[IPC Server Status] - Client Connected");

                        // ----------------------------------------------------------------------------------------------------------------
                        // Received a request from client.
                        string message;
                        bool   finishRead = false;
                        do
                        {
                            byte[] bRequest = new byte[IPCServer.BufferSize];
                            int    cbRequest = bRequest.Length, cbRead;

                            finishRead = NativeMethod.ReadFile(
                                hNamedPipe,             // Handle of the pipe
                                bRequest,               // Buffer to receive data
                                cbRequest,              // Size of buffer in bytes
                                out cbRead,             // Number of bytes read
                                IntPtr.Zero             // Not overlapped
                                );

                            if (!finishRead && Marshal.GetLastWin32Error() != ERROR_MORE_DATA)
                            {
                                throw new Win32Exception();
                            }

                            // UTF8-encode the received byte array and trim all the '\0' characters at the end.
                            message = Encoding.UTF8.GetString(bRequest).Replace("\0", "");
                            Console.WriteLine("[IPC Server Received {0} bytes] Message: {1}\r\n", cbRead, message);
                        }while (!finishRead); // Repeat loop if ERROR_MORE_DATA

                        // If message is not KILL_SERVER, then process client request
                        if (message != "KILL_SERVER")
                        {
                            //Get our message header and data
                            string[] msgArray = message.Split(new string[] { "|:|" }, StringSplitOptions.None);
                            string   header   = msgArray[0];
                            string   data     = msgArray[1];

                            // Process Client Requests Here based off request header
                            Console.WriteLine("    Message Header: " + header);
                            Order order = JsonConvert.DeserializeObject <Order>(data);
                            Console.WriteLine("    Message Data: {0} ordered {1} {2}, delivery address: {3}\r\n", order.CustomerName, order.Quantity, order.ProductName, order.Address);
                        }

                        // ----------------------------------------------------------------------------------------------------------------
                        // Send a message received response to client.
                        string rmessage = IPCServer.ResponseMessage;
                        byte[] bResponse = Encoding.UTF8.GetBytes(rmessage);
                        int    cbResponse = bResponse.Length, cbWritten;

                        if (!NativeMethod.WriteFile(
                                hNamedPipe,             // Handle of the pipe
                                bResponse,              // Message to be written
                                cbResponse,             // Number of bytes to write
                                out cbWritten,          // Number of bytes written
                                IntPtr.Zero             // Not overlapped
                                ))
                        {
                            throw new Win32Exception();
                        }

                        Console.WriteLine("[IPC Server Sent {0} bytes] Message: {1}", cbWritten, rmessage.Replace("\0", ""));

                        if (message == "KILL_SERVER")
                        {
                            KillServerRequested = true;
                        }

                        // ----------------------------------------------------------------------------------------------------------------
                        // Flush the pipe to allow the client to read the pipe's contents before disconnecting. Then disconnect the client's connection.
                        NativeMethod.FlushFileBuffers(hNamedPipe);
                        NativeMethod.DisconnectNamedPipe(hNamedPipe);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message != "Thread was being aborted")
                        {
                            Console.WriteLine("[IPC Server ERROR] - {0}", ex.Message);
                        }

                        hNamedPipe.Close();
                        hNamedPipe.Dispose();
                        NativeMethod.DisconnectNamedPipe(hNamedPipe);
                    }
                    finally
                    {
                        if (hNamedPipe != null)
                        {
                            hNamedPipe.Close();
                            hNamedPipe.Dispose();
                            NativeMethod.DisconnectNamedPipe(hNamedPipe);
                        }
                    }
                }
            }

            if (KillServerRequested)
            {
                _ipcServer.StopServer();
            }
        }
Exemplo n.º 48
0
        public static byte[] CaptureRectangle(Rectangle r)
        {
            IntPtr wndHWND, wndHDC, capHDC, capBMP, prvHDC;

            wndHWND = wndHDC = capHDC = capBMP = prvHDC = IntPtr.Zero;
            byte[] buffer    = null;
            Point  cursorPos = Point.Empty;

            try
            {
                wndHWND = NativeMethod.GetDesktopWindow();      // window handle for desktop

                int x, y, width, height;
                x      = r.X;
                y      = r.Y;
                width  = r.Width;
                height = r.Height;

                wndHDC = NativeMethod.GetDC(wndHWND);           // get context for window

                //	create compatibile capture context and bitmap
                capHDC = NativeMethod.CreateCompatibleDC(wndHDC);
                capBMP = NativeMethod.CreateCompatibleBitmap(wndHDC, width, height);

                //	make sure bitmap non-zero
                if (capBMP == IntPtr.Zero)                              // if no compatible bitmap
                {
                    NativeMethod.ReleaseDC(wndHWND, wndHDC);            //   release window context
                    NativeMethod.DeleteDC(capHDC);                      //   delete capture context
                    throw new Exception("Not create compatible bitmap.");
                }

                //	select compatible bitmap in compatible context
                //	copy window context to compatible context
                //  select previous bitmap back into compatible context
                prvHDC = (IntPtr)NativeMethod.SelectObject(capHDC, capBMP);
                //NativeMethod.BitBlt(capHDC, 0, 0, width, height, wndHDC, x, y, RasterOp.SRCCOPY | RasterOp.CAPTUREBLT);
                NativeMethod.BitBlt(capHDC, 0, 0, width, height, wndHDC, x, y, RasterOp.SRCCOPY);

                NativeMethod.GetCursorPos(out cursorPos);
                cursorPos.X -= r.Left;
                cursorPos.Y -= r.Top;

                // Draw the cursor
                // Always wait cursor, why? So use arrow cursor forever.
                //IntPtr hcur = GetCursor();
                IntPtr hcur = NativeMethod.GetCurrentCursorHandle();

                IconInfo iconInfo = new IconInfo();
                int      hr       = NativeMethod.GetIconInfo(hcur, out iconInfo);
                if (hr != 0)
                {
                    cursorPos.X -= iconInfo.xHotspot;
                    cursorPos.Y -= iconInfo.yHotspot;
                    if (iconInfo.hbmMask != IntPtr.Zero)
                    {
                        NativeMethod.DeleteObject(iconInfo.hbmMask);
                    }
                    if (iconInfo.hbmColor != IntPtr.Zero)
                    {
                        NativeMethod.DeleteObject(iconInfo.hbmColor);
                    }
                }
                NativeMethod.DrawIcon(capHDC, cursorPos.X, cursorPos.Y, hcur);

                NativeMethod.SelectObject(capHDC, prvHDC);

                //	create GDI+ bitmap for window
                Bitmap bitmap = Image.FromHbitmap(capBMP);

                Bitmap b = ImageUtil.AnyBitmapToBitmap24(bitmap);
                bitmap.Dispose();
                bitmap = b;

                buffer = ImageUtil.BitmapToByte(bitmap);
                //buffer = ImageUtil.BitmapToByteEx(bitmap);
                bitmap.Dispose();
            }
            catch (Exception)
            {
            }
            finally
            {
                //	release window and capture resources
                NativeMethod.DeleteObject(capBMP);                              // delete capture bitmap
                NativeMethod.DeleteDC(capHDC);                                  // delete capture context
                NativeMethod.ReleaseDC(wndHWND, wndHDC);                        // release window context
            }
            return(buffer);
        }
Exemplo n.º 49
0
        public void ReplaceMethodWithAttribute()
        {
            DefinedClass klass = new DefinedClass("Spam");
            IFunction method = new NativeMethod(this.DummyMethod);

            klass.SetMethod("foo", method);
            klass.SetValue("foo", 1);

            var result = klass.GetMethod("foo");
            Assert.IsNull(result);
            Assert.IsFalse(klass.HasMethod("foo"));
            Assert.AreEqual(1, klass.GetValue("foo"));
            Assert.IsTrue(klass.HasValue("foo"));
        }