Example #1
0
        private static long CheckMutualExclusion(ILock @lock, int count, int cyclesCount)
        {
            var buckets  = new long[count];
            var finished = new bool[count];
            var total    = 0L;

            ThreadId.ZeroOut();

            var threads = Enumerable.Range(0, count).Select(i =>
            {
                return(new Thread(() =>
                {
                    for (var j = 0; j < cyclesCount; j++)
                    {
                        @lock.Lock();
                        buckets[i]++;
                        total++;
                        @lock.Unlock();
                    }

                    finished[i] = true;
                }));
            });

            foreach (var thread in threads)
            {
                thread.Start();
            }

            while (finished.Any(f => !f))
            {
            }

            return(total);
        }
Example #2
0
        /// <summary>
        /// Compares this ThreadInfo object to another to determine sorting order.
        /// </summary>
        /// <remarks>ThreadInfo instances are sorted by their ThreadId property.</remarks>
        /// <param name="other">The other ThreadInfo object to compare this object to.</param>
        /// <returns>An int which is less than zero, equal to zero, or greater than zero to reflect whether
        /// this ThreadInfo should sort as being less-than, equal to, or greater-than the other
        /// ThreadInfo, respectively.</returns>
        public int CompareTo(ThreadInfo other)
        {
            if (ReferenceEquals(other, null))
            {
                return(1); // We're not null, so we're greater than anything that is null.
            }
            if (ReferenceEquals(this, other))
            {
                return(0); // Refers to the same instance, so obviously we're equal.
            }
            // But in general, we compare first based on ThreadId.
            int compare = ThreadId.CompareTo(other.ThreadId);

            // Unfortunately, ThreadId isn't as unique as we thought, so do some follow-up compares.
            if (compare == 0)
            {
                compare = m_Packet.ThreadIndex.CompareTo(other.ThreadIndex);
            }

            if (compare == 0)
            {
                compare = m_Packet.Timestamp.CompareTo(other.Packet.Timestamp);
            }

            if (compare == 0)
            {
                compare = m_Packet.Sequence.CompareTo(other.Packet.Sequence);
            }

            if (compare == 0)
            {
                compare = Id.CompareTo(other.Id); // Finally, compare by Guid if we have to.
            }
            return(compare);
        }
 public void VirtualMachineStart(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId threadId)
 {
     ThreadReference thread = VirtualMachine.GetMirrorOf(threadId);
     EventRequest request = VirtualMachine.EventRequestManager.GetEventRequest(EventKind.VirtualMachineStart, requestId);
     ThreadEventArgs e = new ThreadEventArgs(VirtualMachine, (SuspendPolicy)suspendPolicy, request, thread);
     VirtualMachine.EventQueue.OnVirtualMachineStart(e);
 }
Example #4
0
 /// <summary>
 /// Default ctor
 /// </summary>
 internal DebugThread(DebugProgram program, EngineEventCallback eventCallback, ThreadManager manager, ThreadId threadId, int tid)
     : base(threadId, manager)
 {
     this.program = program;
     this.eventCallback = eventCallback;
     this.tid = tid;
 }
Example #5
0
        /// <summary>
        /// Handle Thread Status messages
        /// </summary>
        internal static void HandleTHST(Chunk chunk, Action <DalvikEvent> onEvent)
        {
            var data      = chunk.Data;
            var hdrLength = data.GetByte();
            var entryLen  = data.GetByte();
            var count     = data.GetInt16();

            data.Skip(hdrLength - 4);

            var list = new List <ThreadStatusInfo>();

            for (var i = 0; i < count; i++)
            {
                var id       = new ThreadId(data, 4);
                var state    = data.GetByte();
                var tid      = data.GetInt();
                var utime    = data.GetInt();
                var stime    = data.GetInt();
                var isDaemon = data.GetByte();
                data.Skip(entryLen - 18);

                DLog.Debug(DContext.DebuggerLibEvent, "THST id={0}, state={1}, tid={2}, utime={3}, stime={4}", id, state, tid, utime, stime);

                list.Add(new ThreadStatusInfo(id, (ThreadStates)state));
            }
            onEvent(new ThreadStatus(list));
        }
Example #6
0
 /// <summary>
 /// Try to get a thread by it's id.
 /// </summary>
 public bool TryGet(ThreadId id, out DalvikThread thread)
 {
     lock (threadsLock)
     {
         return threads.TryGetValue(id, out thread);
     }
 }
Example #7
0
 /// <summary>
 /// Returns the value of one or more local variables in a given frame. Each variable must be visible at the frame's code index. 
 /// Even if local variable information is not available, values can be retrieved if the front-end is able to determine the correct 
 /// local variable index. (Typically, this index can be determined for method arguments from the method signature without access to 
 /// the local variable table information.)
 /// </summary>
 public Task<List<Value>> GetValuesAsync(ThreadId threadId, FrameId frameId, SlotRequest[] slots)
 {
     var conn = ConnectionOrError;
     DLog.Debug(DContext.DebuggerLibCommands, () => string.Format("StackFrame.GetValues {0}", string.Join(", ", slots.Select(x => x.ToString()))));
     var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 1, threadId.Size + frameId.Size + 4 + (slots.Length * 5), 
         x => {
             var data = x.Data;
             threadId.WriteTo(data);
             frameId.WriteTo(data);
             data.SetInt(slots.Length);
             foreach (var slot in slots)
             {
                 data.SetInt(slot.Slot);
                 data.SetByte((byte) slot.Tag);
             }
         }));
     return t.ContinueWith(x => {
         x.ForwardException();
         var result = x.Result;
         result.ThrowOnError();
         var data = result.Data;
         var count = data.GetInt();
         var list = new List<Value>(count);
         for (var i = 0; i < count; i++ )
         {
             var value = new Value(data);
             list.Add(value);
         }
         return list;
     });
 }
            /// <summary>
            /// Gets the current call stack of the thread with given id.
            /// </summary>
            public Task<List<Tuple<FrameId, Location>>> FramesAsync(ThreadId id, int length = -1)
            {
                var conn = ConnectionOrError;
                var sizeInfo = conn.GetIdSizeInfo();
                var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 6, sizeInfo.ObjectIdSize + 8,
                    x => {
                        id.WriteTo(x.Data);
                        x.Data.SetInt(0); // start frame
                        x.Data.SetInt(length); // length -1 == all
                    }));
                return t.ContinueWith(x => {
                    x.ForwardException();
                    var result = x.Result;
                    result.ThrowOnError();

                    var count = result.Data.GetInt();
                    var list = new List<Tuple<FrameId, Location>>(count);
                    for (var i = 0; i < count; i++)
                    {
                        var frame = new FrameId(result.Data, sizeInfo);
                        var location = new Location(result.Data);
                        list.Add(Tuple.Create(frame, location));
                    }
                    return list;
                });
            }
Example #9
0
        internal int GetSuspendCount(ThreadId threadId)
        {
            int result;

            VirtualMachine.SuspendCounts.TryGetValue(threadId, out result);
            return(result);
        }
        /// <summary>
        /// 接收
        /// </summary>
        public void receive()
        {
            string filename = frm.fileNames[ThreadId];     // 线程临时文件

            byte[]     buffer   = new byte[_bufferSize];   // 接收缓冲区
            int        readSize = 0;                       // 接收字节数
            FileStream fs       = new FileStream(filename, System.IO.FileMode.Create);
            Stream     ns       = null;

            Console.WriteLine("线程[" + ThreadId.ToString() + "] 开始接收......");

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.AddRange(frm.StartPos[ThreadId], frm.StartPos[ThreadId] + frm.fileSize[ThreadId]);
                ns       = request.GetResponse().GetResponseStream();
                readSize = ns.Read(buffer, 0, _bufferSize);
                Console.WriteLine("线程[" + ThreadId.ToString() + "] 正在接收 " + readSize);
                while (readSize > 0)
                {
                    fs.Write(buffer, 0, readSize);
                    readSize = ns.Read(buffer, 0, _bufferSize);
//                    Console.WriteLine("线程[" + ThreadId.ToString() + "] 正在接收 " + readSize);
                }
                fs.Close();
                ns.Close();
            }
            catch (Exception er)
            {
                MessageBox.Show(er.Message);
                fs.Close();
            }
            Console.WriteLine("进程[" + ThreadId.ToString() + "] 结束!");
            frm.threadStatus[ThreadId] = true;
        }
Example #11
0
 public int CompareTo(Job other)
 {
     //EndOfProcessing of processin then thread id
     return((EndOfProcessing == other.EndOfProcessing)
         ? ThreadId.CompareTo(other.ThreadId)
         : EndOfProcessing.CompareTo(other.EndOfProcessing));
 }
Example #12
0
        /// <summary>
        /// Abstracts and returns the spawned thread.
        /// </summary>
        /// <param name="parent">Parent</param>
        /// <param name="impl">Implementation</param>
        /// <param name="tidExpr">Expr</param>
        /// <param name="spawner">CallCmd</param>
        private Thread GetAbstractSpawnedThread(Thread parent, Implementation impl, Expr tidExpr, CallCmd spawner)
        {
            ThreadId tid = this.GetAbstractThreadId(tidExpr, impl, spawner);

            string threadName = "";

            if (spawner.Ins[2] is IdentifierExpr)
            {
                threadName = (spawner.Ins[2] as IdentifierExpr).Name;
            }
            else if (spawner.Ins[2] is NAryExpr)
            {
                var threadExpr = spawner.Ins[2] as NAryExpr;
                if (threadExpr.Fun.FunctionName.StartsWith("$bitcast."))
                {
                    threadName = (threadExpr.Args[0] as IdentifierExpr).Name;
                }
            }

            var thread = Thread.Create(this.AC, tid, threadName, spawner.Ins[3], parent);

            parent.AddChild(thread);

            if (ToolCommandLineOptions.Get().SuperVerboseMode)
            {
                Output.PrintLine("..... {0} spawns {1}",
                                 parent, thread);
            }

            return(thread);
        }
Example #13
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="threadId">The ID of the database.</param>
        /// <param name="listenOptions">The human-readable name for the database.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async IAsyncEnumerable <ListenAction <T> > ListenAsync <T>(ThreadId threadId, IEnumerable <ListenOption> listenOptions, [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            ListenRequest request = new()
            {
                DbID = ByteString.CopyFrom(threadId.Bytes),
            };

            IEnumerable <ListenRequest.Types.Filter> filters = listenOptions.Select(o =>
                                                                                    new ListenRequest.Types.Filter()
            {
                CollectionName = o.CollectionName,
                InstanceID     = o.InstanceId ?? string.Empty,
                Action         = (ListenRequest.Types.Filter.Types.Action)o.Action
            });

            request.Filters.AddRange(filters);

            using AsyncServerStreamingCall <ListenReply> call = _apiClient.Listen(request, headers: _threadContext.Metadata, cancellationToken: cancellationToken);

            await foreach (ListenReply message in call.ResponseStream.ReadAllAsync(cancellationToken))
            {
                if (message != null)
                {
                    ListenAction <T> action = new()
                    {
                        Collection = message.CollectionName,
                        Action     = (ActionType)message.Action,
                        InstanceId = message.InstanceID,
                        Instance   = JsonSerializer.Deserialize <T>(message.Instance.ToStringUtf8())
                    };

                    yield return(action);
                }
            }
        }
Example #14
0
 public Transaction(Context.IThreadContext threadContext, API.APIClient apiClient, ThreadId threadId, string collectionName)
 {
     this.ThreadContext = threadContext;
     Client             = apiClient;
     ThreadId           = threadId;
     CollectionName     = collectionName;
 }
Example #15
0
 /// <summary>
 /// Try to get a thread by it's id.
 /// </summary>
 public bool TryGet(ThreadId id, out DalvikThread thread)
 {
     lock (threadsLock)
     {
         return(threads.TryGetValue(id, out thread));
     }
 }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="address"></param>
        /// <param name="key"></param>
        /// <param name="collections"></param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <ThreadId> NewDbFromAdd(string address, string key, IList <Models.CollectionInfo> collections, CancellationToken cancellationToken = default)
        {
            Multiaddress addr = Multiaddress.Decode(address);

            byte[] keyBytes = ThreadKey.FromString(key).Bytes;

            NewDBFromAddrRequest request = new()
            {
                Addr = ByteString.CopyFrom(addr.ToBytes()),
                Key  = ByteString.CopyFrom(keyBytes)
            };

            if (collections != null)
            {
                //TODO: Finish mapping
                request.Collections.AddRange(collections.Select(c =>
                {
                    return(_mapper.Map <Grpc.CollectionConfig>(c));
                }).ToArray());
            }

            await _apiClient.NewDBFromAddrAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

            //TODO: Get the threadID and Address
            string threadId = string.Empty;

            return(ThreadId.FromString(threadId));
        }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <IDictionary <string, GetDBInfoReply> > ListDBsAsync(CancellationToken cancellationToken = default)
        {
            ListDBsRequest request = new();

            ListDBsReply list = await _apiClient.ListDBsAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

            return(list.Dbs.ToDictionary(db => ThreadId.FromBytes(db.DbID.ToByteArray()).ToString(), db => db.Info));
        }
Example #18
0
        public static ThreadId GetThreadId(Thread handle)
        {
            ThreadId threadId = ThreadId.Worker;

            try { threadId = threadLibrary[handle]; }
            catch (Exception) { }
            return(threadId);
        }
 public ServerThread([NotNull] Settings settings, [NotNull] ThreadId threadId, [NotNull] DistLogger logger, [NotNull] DistLogger errorLogger)
 {
     _settings    = settings;
     _threadId    = threadId;
     _logger      = logger;
     _errorLogger = errorLogger;
     logger.Info("Initializing Server", _threadId);
 }
Example #20
0
 public static EventRequestModifier ThreadFilter(ThreadId thread)
 {
     return new EventRequestModifier()
     {
         Kind = ModifierKind.ThreadFilter,
         Thread = thread,
     };
 }
Example #21
0
        public void Should_Be_Able_To_Create_A_RandomID()
        {
            ThreadId i = ThreadId.FromRandom(Variant.Raw, 16);

            Assert.NotNull(i);
            Assert.Equal(18, i.Bytes.Length);
            Assert.True(i.IsDefined);
        }
 public override int GetHashCode()
 {
     unchecked
     {
         int hash = 17;
         hash = hash * 23 + TitleUnicode.GetHashCode();
         hash = hash * 23 + TitleRoman.GetHashCode();
         hash = hash * 23 + ArtistUnicode.GetHashCode();
         hash = hash * 23 + ArtistRoman.GetHashCode();
         hash = hash * 23 + Creator.GetHashCode();
         hash = hash * 23 + DiffName.GetHashCode();
         hash = hash * 23 + Mp3Name.GetHashCode();
         hash = hash * 23 + Md5.GetHashCode();
         hash = hash * 23 + OsuFileName.GetHashCode();
         hash = hash * 23 + Tags.GetHashCode();
         hash = hash * 23 + Somestuff.GetHashCode();
         hash = hash * 23 + _state.GetHashCode();
         hash = hash * 23 + Circles.GetHashCode();
         hash = hash * 23 + Sliders.GetHashCode();
         hash = hash * 23 + Spinners.GetHashCode();
         hash = hash * 23 + EditDate.GetHashCode();
         hash = hash * 23 + ApproachRate.GetHashCode();
         hash = hash * 23 + CircleSize.GetHashCode();
         hash = hash * 23 + HpDrainRate.GetHashCode();
         hash = hash * 23 + OverallDifficulty.GetHashCode();
         hash = hash * 23 + SliderVelocity.GetHashCode();
         hash = hash * 23 + DrainingTime.GetHashCode();
         hash = hash * 23 + TotalTime.GetHashCode();
         hash = hash * 23 + PreviewTime.GetHashCode();
         hash = hash * 23 + MapId.GetHashCode();
         hash = hash * 23 + MapSetId.GetHashCode();
         hash = hash * 23 + ThreadId.GetHashCode();
         hash = hash * 23 + OsuGrade.GetHashCode();
         hash = hash * 23 + TaikoGrade.GetHashCode();
         hash = hash * 23 + CatchGrade.GetHashCode();
         hash = hash * 23 + ManiaGrade.GetHashCode();
         hash = hash * 23 + Offset.GetHashCode();
         hash = hash * 23 + StackLeniency.GetHashCode();
         hash = hash * 23 + PlayMode.GetHashCode();
         hash = hash * 23 + Source.GetHashCode();
         hash = hash * 23 + AudioOffset.GetHashCode();
         hash = hash * 23 + LetterBox.GetHashCode();
         hash = hash * 23 + Played.GetHashCode();
         hash = hash * 23 + LastPlayed.GetHashCode();
         hash = hash * 23 + IsOsz2.GetHashCode();
         hash = hash * 23 + Dir.GetHashCode();
         //hash = hash * 23 + LastSync.GetHashCode(); //This value is updated by osu even if no changes were made to the actual data
         hash = hash * 23 + DisableHitsounds.GetHashCode();
         hash = hash * 23 + DisableSkin.GetHashCode();
         hash = hash * 23 + DisableSb.GetHashCode();
         hash = hash * 23 + BgDim.GetHashCode();
         hash = hash * 23 + ModPpStars.GetHashCode();
         hash = hash * 23 + MaxBpm.GetHashCode();
         hash = hash * 23 + MinBpm.GetHashCode();
         hash = hash * 23 + MainBpm.GetHashCode();
         return(hash);
     }
 }
Example #23
0
        public void Should_Be_Able_To_Round_Trip_To_And_From_Bytes()
        {
            ThreadId i = ThreadId.FromRandom(Variant.Raw, 16);

            byte[]   b = i.Bytes;
            ThreadId n = ThreadId.FromBytes(b);

            Assert.Equal(n, i);
        }
Example #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="threadId">The ID of the database.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task DeleteDBAsync(ThreadId threadId, CancellationToken cancellationToken = default)
        {
            DeleteDBRequest request = new()
            {
                DbID = ByteString.CopyFrom(threadId.Bytes)
            };

            await _apiClient.DeleteDBAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);
        }
Example #25
0
        internal ThreadReference GetMirrorOf(ThreadId thread)
        {
            if (thread == default(ThreadId))
            {
                return(null);
            }

            return(new ThreadReference(this, thread));
        }
            public void Breakpoint(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId threadId, Types.Location location)
            {
                ThreadReference thread = VirtualMachine.GetMirrorOf(threadId);
                EventRequest request = VirtualMachine.EventRequestManager.GetEventRequest(EventKind.Breakpoint, requestId);
                Location loc = VirtualMachine.GetMirrorOf(location);

                ThreadLocationEventArgs e = new ThreadLocationEventArgs(VirtualMachine, (SuspendPolicy)suspendPolicy, request, thread, loc);
                VirtualMachine.EventQueue.OnBreakpoint(e);
            }
Example #27
0
 protected virtual void doWork()
 {
     ThreadState = System.Threading.ThreadState.Running;
     m_SimpleMethod();
     ThreadState = System.Threading.ThreadState.Stopped;
     if (threadCallback != null)
     {
         threadCallback(ThreadId.ToString());
     }
 }
Example #28
0
 protected virtual void doWorkP(object parms)
 {
     ThreadState = System.Threading.ThreadState.Running;
     m_ParamMethod(parms);
     ThreadState = System.Threading.ThreadState.Stopped;
     if (threadCallback != null)
     {
         threadCallback(ThreadId.ToString());
     }
 }
Example #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="threadId">The ID of the database.</param>
        /// <param name="config"></param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task UpdateCollectionAsync(ThreadId threadId, Models.CollectionInfo config, CancellationToken cancellationToken = default)
        {
            UpdateCollectionRequest request = new()
            {
                Config = _mapper.Map <Grpc.CollectionConfig>(config),
                DbID   = ByteString.CopyFrom(threadId.Bytes)
            };

            await _apiClient.UpdateCollectionAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);
        }
        public void Log(string logInfo)
        {
            if (_logUtility == null)
            {
                _logUtility = new LogUtility();
            }
            string str = string.Format("Thread {0}: {1}", ThreadId.ToString(), logInfo);

            _logUtility.Log(str);
        }
Example #31
0
        /// <summary>
        /// Abstracts the blocked thread.
        /// </summary>
        /// <param name="parent">Parent</param>
        /// <param name="impl">Implementation</param>
        /// <param name="tidExpr">Expr</param>
        /// <param name="spawner">CallCmd</param>
        private void AbstractBlockedThread(Thread parent, Implementation impl, Expr tidExpr, CallCmd spawner)
        {
            ThreadId tid = this.GetAbstractThreadId(tidExpr, impl, spawner);

            if (ToolCommandLineOptions.Get().SuperVerboseMode)
            {
                Output.PrintLine("..... {0} blocks unidentified thread with id '{1}'",
                                 parent, tid.Id);
            }
        }
Example #32
0
        public override string ToString()
        {
            var t = ThreadId.ToString();

            if (t.Length == 1)
            {
                t = $"{t} ";
            }

            return($"[{t}] {Message}");
        }
 /// <summary>
 /// Resume the thread with given id.
 /// </summary>
 public Task ResumeAsync(ThreadId id)
 {
     var conn = ConnectionOrError;
     var sizeInfo = conn.GetIdSizeInfo();
     var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 3, sizeInfo.ObjectIdSize, x => id.WriteTo(x.Data)));
     return t.ContinueWith(x => {
         x.ForwardException();
         var result = x.Result;
         result.ThrowOnError();
     });
 }
 public override string ToString()
 {
     return(string.Format(DefaultNumberedMessageFormat,
                          ThreadHashCode.ToString(),
                          ThreadId.ToString(),
                          ApplicationName,
                          ProcessId,
                          Utc.ToShortDateString(),
                          Utc.ToShortTimeString(),
                          Message));
 }
Example #35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="threadId">The ID of the database.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <IList <Models.CollectionInfo> > ListCollectionAsync(ThreadId threadId, CancellationToken cancellationToken = default)
        {
            ListCollectionsRequest request = new()
            {
                DbID = ByteString.CopyFrom(threadId.Bytes)
            };

            ListCollectionsReply reply = await _apiClient.ListCollectionsAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

            return(_mapper.Map <List <Models.CollectionInfo> >(reply.Collections.ToList()));
        }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Id != null ? Id.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ThreadId != null ? ThreadId.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (CommentText != null ? CommentText.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Sender != null ? Sender.GetHashCode() : 0);
         return(hashCode);
     }
 }
Example #37
0
        public void Save()
        {
            Query savePost = new Query("INSERT INTO POSTS (thread_id, subject, message, poster, image) VALUES(@ThreadId, @Subject, @Message, @Poster, @Image)");

            savePost.AddParameter("@ThreadId", ThreadId.ToString());
            savePost.AddParameter("@Subject", Subject);
            savePost.AddParameter("@Message", Message);
            savePost.AddParameter("@Poster", Poster);
            savePost.AddParameter("@Image", Image);
            savePost.Execute();
            Console.WriteLine("SUBJECT: " + Subject);
        }
Example #38
0
        public IJsonValue ExportToJsonObject()
        {
            var buffer = new JsonObject();

            buffer.SetNamedValue("Id", Id.ToJsonValue());
            buffer.SetNamedValue("Timestamp", Timestamp.ToJsonValue());
            buffer.SetNamedValue("ThreadId", ThreadId.ToJsonValue());
            buffer.SetNamedValue("Severity", Severity.ToJsonValue());
            buffer.SetNamedValue("Message", Message.ToJsonValue());

            return(buffer);
        }
Example #39
0
            /// <summary>
            /// Returns the value of one or more local variables in a given frame. Each variable must be visible at the frame's code index. 
            /// Even if local variable information is not available, values can be retrieved if the front-end is able to determine the correct 
            /// local variable index. (Typically, this index can be determined for method arguments from the method signature without access to 
            /// the local variable table information.)
            /// </summary>
            public Task<List<Value>> GetValuesAsync(ThreadId threadId, FrameId frameId, SlotRequest[] slots)
            {
                var conn = ConnectionOrError;
                DLog.Debug(DContext.DebuggerLibCommands, () => string.Format("StackFrame.GetValues {0}", string.Join(", ", slots.Select(x => x.ToString()))));
                var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 1, threadId.Size + frameId.Size + 4 + (slots.Length * 5),
                    x => {
                        var data = x.Data;
                        threadId.WriteTo(data);
                        frameId.WriteTo(data);
                        data.SetInt(slots.Length);
                        foreach (var slot in slots)
                        {
                            if (slot.Slot == 1000)
                            {
                                // I have seen this crash the VM on a CyanogenMod Android 4.4.4
                                // Samsung GT-I9195. Might be a bug in CyanogenMod.
                                // https://android.googlesource.com/platform/art/+/ffcd9d25199a944625bd3c9a766349c23dcbdb66/runtime/debugger.cc
                                DLog.Debug(DContext.DebuggerLibEvent, "accessing variable with Slot=1000");
                            }

                            data.SetInt(slot.Slot);
                            data.SetByte((byte) slot.Tag);
                        }
                    }));
                return t.ContinueWith(x => {
                    x.ForwardException();
                    var result = x.Result;
                    result.ThrowOnError();
                    var data = result.Data;
                    var count = data.GetInt();
                    var list = new List<Value>(count);
                    for (var i = 0; i < count; i++ )
                    {
                        var value = new Value(data);
                        list.Add(value);
                    }
                    return list;
                });
            }
Example #40
0
 internal ThreadReference(VirtualMachine virtualMachine, ThreadId threadId, IReferenceType threadType)
     : base(virtualMachine, threadId, threadType)
 {
     Contract.Requires(virtualMachine != null);
 }
        public Error SetValues(ThreadId thread, FrameId frame, int[] slots, Value[] values)
        {
            int frameIndex = (int)frame.Handle;
            FrameLocationData[] frames = new FrameLocationData[1];
            Error errorCode = GetRawThreadFrames(out frames, thread, frameIndex, 1);
            if (errorCode != Error.None)
                return errorCode;

            frame = frames[0].FrameId;

            throw new NotImplementedException();
        }
        public Error GetThisObject(out TaggedObjectId thisObject, ThreadId thread, FrameId frame)
        {
            int frameIndex = (int)frame.Handle;
            FrameLocationData[] frames = new FrameLocationData[1];
            Error errorCode = GetRawThreadFrames(out frames, thread, frameIndex, 1);
            if (errorCode != Error.None)
            {
                thisObject = default(TaggedObjectId);
                return errorCode;
            }

            frame = frames[0].FrameId;

            byte[] packet = new byte[HeaderSize + ThreadIdSize + FrameIdSize];
            int id = GetMessageId();
            SerializeHeader(packet, id, StackFrameCommand.ThisObject);
            WriteObjectId(packet, HeaderSize, thread);
            WriteFrameId(packet, HeaderSize + ThreadIdSize, frame);

            byte[] response = SendPacket(id, packet);
            errorCode = ReadErrorCode(response);
            if (errorCode != Error.None)
            {
                thisObject = default(TaggedObjectId);
                return errorCode;
            }

            int offset = HeaderSize;
            thisObject = ReadTaggedObjectId(response, ref offset);
            return Error.None;
        }
 public void MethodEntry(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId thread, Types.Location location)
 {
     throw new NotImplementedException();
 }
        public Error GetValues(out Value[] values, ThreadId thread, FrameId frame, int[] slots)
        {
            int frameIndex = (int)frame.Handle;
            FrameLocationData[] frames = new FrameLocationData[1];
            Error errorCode = GetRawThreadFrames(out frames, thread, frameIndex, 1);
            if (errorCode != Error.None)
            {
                values = null;
                return errorCode;
            }

            frame = frames[0].FrameId;

            VariableData[] variableData;
            errorCode = GetMethodVariableTable(out variableData, frames[0].Location.Class, frames[0].Location.Method);
            if (errorCode != Error.None)
            {
                values = null;
                return errorCode;
            }

            Tag[] tags = new Tag[slots.Length];
            for (int i = 0; i < slots.Length; i++)
            {
                tags[i] = Tag.Object;
                foreach (VariableData variable in variableData)
                {
                    if (variable.Slot != slots[i])
                        continue;

                    if (variable.CodeIndex > frames[0].Location.Index)
                        continue;

                    if (variable.CodeIndex + variable.Length <= frames[0].Location.Index)
                        continue;

                    if (string.IsNullOrEmpty(variable.Signature))
                        continue;

                    tags[i] = (Tag)variable.Signature[0];
                    break;
                }
            }

            byte[] packet = new byte[HeaderSize + ThreadIdSize + FrameIdSize + sizeof(int) + (slots.Length * (sizeof(int) + sizeof(byte)))];
            int id = GetMessageId();
            SerializeHeader(packet, id, StackFrameCommand.GetValues);
            WriteObjectId(packet, HeaderSize, thread);
            WriteFrameId(packet, HeaderSize + ThreadIdSize, frame);
            WriteInt32(packet, HeaderSize + ThreadIdSize + FrameIdSize, slots.Length);

            int baseOffset = HeaderSize + ThreadIdSize + FrameIdSize + sizeof(int);
            for (int i = 0; i < slots.Length; i++)
            {
                int slotOffset = baseOffset + i * (sizeof(int) + sizeof(byte));
                WriteInt32(packet, slotOffset, slots[i]);
                packet[slotOffset + sizeof(int)] = (byte)tags[i];
            }

            byte[] response = SendPacket(id, packet);
            errorCode = ReadErrorCode(response);
            if (errorCode != Error.None)
            {
                values = null;
                return errorCode;
            }

            int offset = HeaderSize;
            int valueCount = ReadInt32(response, ref offset);
            values = new Value[valueCount];
            for (int i = 0; i < valueCount; i++)
            {
                values[i] = ReadValue(response, ref offset);
            }

            return Error.None;
        }
            private jvmtiError ApplySuspendPolicy(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, SuspendPolicy policy, ThreadId eventThread)
            {
                if (policy == SuspendPolicy.EventThread && eventThread == default(ThreadId))
                {
                    return jvmtiError.InvalidThread;
                }

                switch (policy)
                {
                case SuspendPolicy.None:
                    return jvmtiError.None;

                case SuspendPolicy.EventThread:
                    return environment.SuspendThread(nativeEnvironment, eventThread);

                case SuspendPolicy.All:
                    ThreadId[] requestList;
                    JvmtiErrorHandler.ThrowOnFailure(environment.GetAllThreads(nativeEnvironment, out requestList));
                    jvmtiError[] errors;
                    return environment.SuspendThreads(nativeEnvironment, requestList, out errors);

                default:
                    throw new ArgumentException("Invalid suspend policy.");
                }
            }
        public Error GetAllThreads(out ThreadId[] threads)
        {
            byte[] packet = new byte[HeaderSize];
            int id = GetMessageId();
            SerializeHeader(packet, id, VirtualMachineCommand.AllThreads);

            byte[] response = SendPacket(id, packet);
            Error errorCode = ReadErrorCode(response);
            if (errorCode != Error.None)
            {
                threads = null;
                return errorCode;
            }

            int offset = HeaderSize;
            int threadCount = ReadInt32(response, ref offset);
            threads = new ThreadId[threadCount];
            for (int i = 0; i < threadCount; i++)
                threads[i] = (ThreadId)ReadObjectId(response, ref offset);

            return Error.None;
        }
        public Error GetThreadSuspendCount(out int suspendCount, ThreadId thread)
        {
            byte[] packet = new byte[HeaderSize + ThreadIdSize];
            int id = GetMessageId();
            SerializeHeader(packet, id, ThreadReferenceCommand.SuspendCount);
            WriteObjectId(packet, HeaderSize, thread);

            byte[] response = SendPacket(id, packet);
            Error errorCode = ReadErrorCode(response);
            if (errorCode != Error.None)
            {
                suspendCount = 0;
                return errorCode;
            }

            int offset = HeaderSize;
            suspendCount = ReadInt32(response, ref offset);
            return Error.None;
        }
 public void MonitorContendedWaited(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId thread, TaggedObjectId @object, Types.Location location, bool timedOut)
 {
     throw new NotImplementedException();
 }
Example #49
0
 /// <summary>
 /// Create an instance representing the given reference type.
 /// </summary>
 protected virtual DalvikThread CreateThread(ThreadId id)
 {
     return new DalvikThread(id, this);
 }
 public void ClassPrepare(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId threadId, TypeTag typeTag, ReferenceTypeId typeId, string signature, ClassStatus status)
 {
     ThreadReference thread = VirtualMachine.GetMirrorOf(threadId);
     EventRequest request = VirtualMachine.EventRequestManager.GetEventRequest(EventKind.ClassPrepare, requestId);
     ReferenceType type = VirtualMachine.GetMirrorOf(typeTag, typeId);
     ClassPrepareEventArgs e = new ClassPrepareEventArgs(VirtualMachine, (SuspendPolicy)suspendPolicy, request, thread, signature, type);
     VirtualMachine.EventQueue.OnClassPrepare(e);
 }
 public void FieldModification(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId thread, Types.Location location, TypeTag typeTag, ReferenceTypeId typeId, FieldId field, TaggedObjectId @object, Types.Value newValue)
 {
     throw new NotImplementedException();
 }
            private void SendClassPrepareEvent(JvmtiEnvironment environment, EventFilter filter, ThreadId threadId, TaggedReferenceTypeId classId, string signature, ClassStatus classStatus, bool preventSuspend)
            {
                if (!VirtualMachine.IsAgentThread.Value)
                {
                    // ignore events before VMInit
                    if (AgentEventDispatcher == null)
                        return;

                    // dispatch this call to an agent thread
                    Action<JvmtiEnvironment, EventFilter, ThreadId, TaggedReferenceTypeId, string, ClassStatus, bool> method = SendClassPrepareEvent;
                    AgentEventDispatcher.Invoke(method, environment, filter, threadId, classId, signature, classStatus, preventSuspend);
                    return;
                }

                JniEnvironment nativeEnvironment;
                JniErrorHandler.ThrowOnFailure(VirtualMachine.AttachCurrentThreadAsDaemon(environment, out nativeEnvironment, true));

                SuspendPolicy suspendPolicy = preventSuspend ? SuspendPolicy.None : filter.SuspendPolicy;
                if (!preventSuspend)
                    ApplySuspendPolicy(environment, nativeEnvironment, filter.SuspendPolicy, threadId);

                Callback.ClassPrepare(suspendPolicy, filter.RequestId, threadId, classId.TypeTag, classId.TypeId, signature, classStatus);
            }
 public Error GetThreadGroupChildren(out ThreadId[] childThreads, out ThreadGroupId[] childGroups, ThreadGroupId group)
 {
     throw new NotImplementedException();
 }
            private void SendSingleStepEvent(JvmtiEnvironment environment, EventFilter filter, ThreadId threadId, Location location)
            {
                if (!VirtualMachine.IsAgentThread.Value)
                {
                    // ignore events before VMInit
                    if (AgentEventDispatcher == null)
                        return;

                    // dispatch this call to an agent thread
                    Action<JvmtiEnvironment, EventFilter, ThreadId, Location> invokeMethod = SendSingleStepEvent;
                    AgentEventDispatcher.Invoke(invokeMethod, environment, filter, threadId, location);
                    return;
                }

                JniEnvironment nativeEnvironment;
                JniErrorHandler.ThrowOnFailure(VirtualMachine.AttachCurrentThreadAsDaemon(environment, out nativeEnvironment, false));

                ApplySuspendPolicy(environment, nativeEnvironment, filter.SuspendPolicy, threadId);
                Callback.SingleStep(filter.SuspendPolicy, filter.RequestId, threadId, location);
            }
 public void MethodExit(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId thread, Types.Location location, Types.Value returnValue)
 {
     throw new NotImplementedException();
 }
        public Error PopFrames(ThreadId thread, FrameId frame)
        {
            int frameIndex = (int)frame.Handle;
            FrameLocationData[] frames = new FrameLocationData[1];
            Error errorCode = GetRawThreadFrames(out frames, thread, frameIndex, 1);
            if (errorCode != Error.None)
                return errorCode;

            frame = frames[0].FrameId;

            byte[] packet = new byte[HeaderSize + ThreadIdSize + FrameIdSize];
            int id = GetMessageId();
            SerializeHeader(packet, id, StackFrameCommand.PopFrames);
            WriteObjectId(packet, HeaderSize, thread);
            WriteFrameId(packet, HeaderSize + ThreadIdSize, frame);

            byte[] response = SendPacket(id, packet);
            return ReadErrorCode(response);
        }
 public void Exception(Types.SuspendPolicy suspendPolicy, RequestId requestId, ThreadId threadId, Types.Location location, TaggedObjectId exception, Types.Location catchLocation)
 {
     EventRequest request = VirtualMachine.EventRequestManager.GetEventRequest(EventKind.Exception, requestId);
     ThreadReference thread = VirtualMachine.GetMirrorOf(threadId);
     Location loc = VirtualMachine.GetMirrorOf(location);
     ObjectReference exceptionReference = VirtualMachine.GetMirrorOf(exception);
     Location catchLoc = VirtualMachine.GetMirrorOf(catchLocation);
     ExceptionEventArgs e = new ExceptionEventArgs(VirtualMachine, (SuspendPolicy)suspendPolicy, request, thread, loc, exceptionReference, catchLoc);
     VirtualMachine.EventQueue.OnException(e);
 }
 public Error StopThread(ThreadId thread, ObjectId throwable)
 {
     throw new NotImplementedException();
 }
 public Error GetThreadCurrentContendedMonitor(out TaggedObjectId monitor, ThreadId thread)
 {
     throw new NotImplementedException();
 }
 public Error InterruptThread(ThreadId thread)
 {
     throw new NotImplementedException();
 }