Skip to main content
summaryrefslogtreecommitdiffstats
blob: eebb3013c65bb0d6f75686fe34c7acf6080dd459 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/*******************************************************************************
 * Copyright (c) 2008, 2010 Wind River Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.cdt.examples.dsf.pda.service;

import java.util.Hashtable;
import java.util.Map;

import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.Immutable;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.datamodel.AbstractDMContext;
import org.eclipse.cdt.dsf.datamodel.AbstractDMEvent;
import org.eclipse.cdt.dsf.datamodel.DMContexts;
import org.eclipse.cdt.dsf.datamodel.IDMContext;
import org.eclipse.cdt.dsf.debug.service.ICachingService;
import org.eclipse.cdt.dsf.debug.service.IExpressions;
import org.eclipse.cdt.dsf.debug.service.IRegisters.IRegisterDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IResumedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.ISuspendedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.StateChangeReason;
import org.eclipse.cdt.dsf.debug.service.IStack.IFrameDMContext;
import org.eclipse.cdt.dsf.debug.service.command.CommandCache;
import org.eclipse.cdt.dsf.service.AbstractDsfService;
import org.eclipse.cdt.dsf.service.DsfServiceEventHandler;
import org.eclipse.cdt.dsf.service.DsfSession;
import org.eclipse.cdt.examples.dsf.pda.PDAPlugin;
import org.eclipse.cdt.examples.dsf.pda.service.commands.PDAChildrenCommand;
import org.eclipse.cdt.examples.dsf.pda.service.commands.PDACommandResult;
import org.eclipse.cdt.examples.dsf.pda.service.commands.PDAListResult;
import org.eclipse.cdt.examples.dsf.pda.service.commands.PDASetVarCommand;
import org.eclipse.cdt.examples.dsf.pda.service.commands.PDAVarCommand;
import org.osgi.framework.BundleContext;

/**
 * 
 */
public class PDAExpressions extends AbstractDsfService implements ICachingService, IExpressions {

    @Immutable
    private static class ExpressionDMContext extends AbstractDMContext implements IExpressionDMContext {

        final private String fExpression;
        
        ExpressionDMContext(String sessionId, IFrameDMContext frameDmc, String expressin) {
            super(sessionId, new IDMContext[] { frameDmc });
            fExpression = expressin;
        }

        public String getExpression() { 
            return fExpression;
        }
        
        @Override
        public boolean equals(Object other) {
            return super.baseEquals(other) && ((ExpressionDMContext)other).fExpression.equals(fExpression);
        }
        
        @Override
        public int hashCode() {
            return super.baseHashCode() + fExpression.hashCode();
        }
        
        @Override
        public String toString() { 
            return baseToString() + ".expression(" + fExpression + ")";  
        }
    }

    /**
     * PDA expressions are simply variables.  Only the variable name 
     * is relevant for its data.
     */
    @Immutable
    private static class ExpressionDMData implements IExpressionDMData {

        final private String fExpression;
        
        public ExpressionDMData(String expression) {
            fExpression = expression;
        }
        
        public BasicType getBasicType() {
            return BasicType.basic;
        }

        public String getEncoding() {
            return null;
        }

        public Map<String, Integer> getEnumerations() {
            return null;
        }

        public String getName() {
            return fExpression;
        }

        public IRegisterDMContext getRegister() {
            return null;
        }

        public String getStringValue() {
            return null;
        }

        public String getTypeId() {
            return null;
        }

        public String getTypeName() {
            return null;
        }

    }

    // @see #createExpression()
    @Immutable
    private static class InvalidExpressionDMContext extends AbstractDMContext implements IExpressionDMContext {
        final private String fExpression;
    
        public InvalidExpressionDMContext(String sessionId, IDMContext parent, String expr) {
            super(sessionId, new IDMContext[] { parent });
            fExpression = expr;
        }
    
        @Override
        public boolean equals(Object other) {
            return super.baseEquals(other) && 
                fExpression == null 
                    ? ((InvalidExpressionDMContext) other).getExpression() == null 
                    : fExpression.equals(((InvalidExpressionDMContext) other).getExpression());
        }
    
        @Override
        public int hashCode() {
            return fExpression == null ? super.baseHashCode() : super.baseHashCode() ^ fExpression.hashCode();
        }
    
        @Override
        public String toString() {
            return baseToString() + ".invalid_expr[" + fExpression + "]"; 
        }
    
        public String getExpression() {
            return fExpression;
        }
    }
    
    @Immutable
    private static class ExpressionChangedDMEvent extends AbstractDMEvent<IExpressionDMContext> 
        implements IExpressionChangedDMEvent 
    {
        ExpressionChangedDMEvent(IExpressionDMContext expression) {
            super(expression);
        }
    }

    
    private PDACommandControl fCommandControl;
    private PDAStack fStack;

    private CommandCache fCommandCache;

    public PDAExpressions(DsfSession session) {
        super(session);
    }

    @Override
    protected BundleContext getBundleContext() {
        return PDAPlugin.getBundleContext();
    }

    @Override
    public void initialize(final RequestMonitor rm) {
        super.initialize(
            new RequestMonitor(getExecutor(), rm) { 
                @Override
                protected void handleSuccess() {
                    doInitialize(rm);
                }});
    }

    private void doInitialize(final RequestMonitor rm) {
        fCommandControl = getServicesTracker().getService(PDACommandControl.class);
        fStack = getServicesTracker().getService(PDAStack.class);
        fCommandCache = new CommandCache(getSession(), fCommandControl);
        fCommandCache.setContextAvailable(fCommandControl.getContext(), true);

        getSession().addServiceEventListener(this, null);
        
        register(new String[]{IExpressions.class.getName(), PDAExpressions.class.getName()}, new Hashtable<String,String>());
        
        rm.done();
    }

    @Override
    public void shutdown(final RequestMonitor rm) {
        getSession().removeServiceEventListener(this);
        fCommandCache.reset();
        super.shutdown(rm);
    }

    public void canWriteExpression(IExpressionDMContext expressionContext, DataRequestMonitor<Boolean> rm) {
        rm.setData(true);
        rm.done();
    }

    public IExpressionDMContext createExpression(IDMContext ctx, String expression) {
        // Create an expression based on the given context and string expression.  
        PDAThreadDMContext threadCtx = DMContexts.getAncestorOfType(ctx, PDAThreadDMContext.class);
        if (threadCtx != null) {
            // The PDA debugger can only evaluate variables as expressions and only
            // in context of a frame, so if a frame is not given, create a top-level frame.
            IFrameDMContext frameCtx = DMContexts.getAncestorOfType(ctx, IFrameDMContext.class);
            if (frameCtx == null) {
                frameCtx = fStack.getFrameDMContext(threadCtx, 0);
            }
            
            return new ExpressionDMContext(getSession().getId(), frameCtx, expression);
        } 
            
        // If the thread cannot be found in context, return an "invalid" 
        // expression context, because a null return value is not allowed.
        // Evaluating an invalid expression context will always yield an 
        // error.
        return new InvalidExpressionDMContext(getSession().getId(), ctx, expression);
    }

    public void getBaseExpressions(IExpressionDMContext exprContext, DataRequestMonitor<IExpressionDMContext[]> rm) {
        PDAPlugin.failRequest(rm, NOT_SUPPORTED, "Not supported");
    }

    public void getExpressionAddressData(IExpressionDMContext dmc, DataRequestMonitor<IExpressionDMAddress> rm) {
        PDAPlugin.failRequest(rm, NOT_SUPPORTED, "Not supported");
    }

    public void getExpressionData(final IExpressionDMContext exprCtx, final DataRequestMonitor<IExpressionDMData> rm) {
        // Since expression data doesn't contain any more information than the 
        // context, it doesn't require any debugger commmands.
        if (exprCtx instanceof ExpressionDMContext) {
            rm.setData(new ExpressionDMData(exprCtx.getExpression()));
            rm.done();
        } else {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid expression context " + exprCtx);
        }
    }

    public void getSubExpressionCount(final IExpressionDMContext exprCtx, final DataRequestMonitor<Integer> rm) {
        if (exprCtx instanceof ExpressionDMContext) {
            final PDAThreadDMContext threadCtx = DMContexts.getAncestorOfType(exprCtx, PDAThreadDMContext.class);
            final IFrameDMContext frameCtx = DMContexts.getAncestorOfType(exprCtx, IFrameDMContext.class);
            
            // First retrieve the stack depth, needed to properly calculate
            // the frame index that is used by the PDAVarCommand. 
            fStack.getStackDepth(
                frameCtx, 0,
                new DataRequestMonitor<Integer>(getExecutor(), rm) {
                    @Override
                    protected void handleSuccess() {
                        // Calculate the frame index.
                        int frameId = getData() - frameCtx.getLevel() - 1;
                        
                        // Send the command to evaluate the variable.
                        fCommandCache.execute(
                            new PDAChildrenCommand(threadCtx, frameId, exprCtx.getExpression()), 
                            new DataRequestMonitor<PDAListResult>(getExecutor(), rm) {
                                @Override
                                protected void handleSuccess() {
                                    rm.setData(getData().fValues.length);
                                    rm.done();
                                }
                            });        
                    }
                });
        } else {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid context");
        }
    }

    public void getSubExpressions(IExpressionDMContext exprCtx, DataRequestMonitor<IExpressionDMContext[]> rm) {
        getSubExpressions(exprCtx, -1, -1, rm);
    }

    public void getSubExpressions(final IExpressionDMContext exprCtx, final int startIndexArg, final int lengthArg,
        final DataRequestMonitor<IExpressionDMContext[]> rm) 
    {
        if (exprCtx instanceof ExpressionDMContext) {
            final PDAThreadDMContext threadCtx = DMContexts.getAncestorOfType(exprCtx, PDAThreadDMContext.class);
            final IFrameDMContext frameCtx = DMContexts.getAncestorOfType(exprCtx, IFrameDMContext.class);
            
            // First retrieve the stack depth, needed to properly calculate
            // the frame index that is used by the PDAVarCommand. 
            fStack.getStackDepth(
                frameCtx, 0,
                new DataRequestMonitor<Integer>(getExecutor(), rm) {
                    @Override
                    protected void handleSuccess() {
                        // Calculate the frame index.
                        int frameId = getData() - frameCtx.getLevel() - 1;
                        
                        // Send the command to evaluate the variable.
                        fCommandCache.execute(
                            new PDAChildrenCommand(threadCtx, frameId, exprCtx.getExpression()), 
                            new DataRequestMonitor<PDAListResult>(getExecutor(), rm) {
                                @Override
                                protected void handleSuccess() {
                                    int start = startIndexArg > 0 ? startIndexArg : 0;
                                    int end = lengthArg > 0 ? (start + lengthArg) : getData().fValues.length;
                                    IExpressionDMContext[] contexts = new IExpressionDMContext[end - start];                                     
                                    for (int i = start; i < end && i < getData().fValues.length; i++) {
                                        contexts[i] = new ExpressionDMContext(
                                            getSession().getId(), frameCtx, getData().fValues[i]);
                                    }
                                    rm.setData(contexts);
                                    rm.done();
                                }
                            });        
                    }
                });
        } else {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid context");
        }
    }

    public void getAvailableFormats(IFormattedDataDMContext dmc, final DataRequestMonitor<String[]> rm) {
        getFormattedExpressionValue(
            new FormattedValueDMContext(this, dmc, NATURAL_FORMAT),
            new DataRequestMonitor<FormattedValueDMData>(getExecutor(), rm) {
                @Override
                protected void handleSuccess() {
                    try {
                        Integer.parseInt(getData().getFormattedValue());
                        rm.setData(new String[] { DECIMAL_FORMAT, HEX_FORMAT, DECIMAL_FORMAT, OCTAL_FORMAT, BINARY_FORMAT });                        
                        rm.done();
                    } catch (NumberFormatException e) {
                        rm.setData(new String[] { STRING_FORMAT });
                        rm.done();
                    }
                }
                
                @Override
                protected void handleErrorOrWarning() {
                    rm.setData(new String[] { STRING_FORMAT });
                    rm.done();
                }
            });
    }

    public FormattedValueDMContext getFormattedValueContext(IFormattedDataDMContext exprCtx, String formatId) {
        // Creates a context that can be used to retrieve a formatted value.
        return new FormattedValueDMContext(this, exprCtx, formatId);
    }

    public void getFormattedExpressionValue(FormattedValueDMContext formattedCtx, 
        final DataRequestMonitor<FormattedValueDMData> rm) 
    {
        final String formatId = formattedCtx.getFormatID();
        final ExpressionDMContext exprCtx = DMContexts.getAncestorOfType(formattedCtx, ExpressionDMContext.class);
        if (exprCtx != null) {
            final PDAThreadDMContext threadCtx = DMContexts.getAncestorOfType(exprCtx, PDAThreadDMContext.class);
            final IFrameDMContext frameCtx = DMContexts.getAncestorOfType(exprCtx, IFrameDMContext.class);
            
            // First retrieve the stack depth, needed to properly calculate
            // the frame index that is used by the PDAVarCommand. 
            fStack.getStackDepth(
                frameCtx, 0,
                new DataRequestMonitor<Integer>(getExecutor(), rm) {
                    @Override
                    protected void handleSuccess() {
                        // Calculate the frame index.
                        int frameId = getData() - frameCtx.getLevel() - 1;
                        
                        // Send the command to evaluate the variable.
                        fCommandCache.execute(
                            new PDAVarCommand(threadCtx, frameId, exprCtx.getExpression()), 
                            new DataRequestMonitor<PDACommandResult>(getExecutor(), rm) {
                                @Override
                                protected void handleSuccess() {
                                    if (NATURAL_FORMAT.equals(formatId) || STRING_FORMAT.equals(formatId)) {
                                        rm.setData(new FormattedValueDMData(getData().fResponseText));
                                        rm.done();
                                    } else {                                        
                                        int result;
                                        try {
                                            int intResult = Integer.parseInt(getData().fResponseText);
                                            String formattedResult = "";
                                            if (HEX_FORMAT.equals(formatId)) {
                                                formattedResult = Integer.toHexString(intResult);
                                                StringBuffer prefix = new StringBuffer("0x");
                                                for (int i = 0; i < 8 - formattedResult.length(); i++) {
                                                    prefix.append('0');
                                                }
                                                prefix.append(formattedResult);
                                                formattedResult = prefix.toString();
                                            } else if (OCTAL_FORMAT.equals(formatId)) {
                                                formattedResult = Integer.toOctalString(intResult);
                                                StringBuffer prefix = new StringBuffer("0c");
                                                for (int i = 0; i < 16 - formattedResult.length(); i++) {
                                                    prefix.append('0');
                                                }
                                                prefix.append(formattedResult);
                                                formattedResult = prefix.toString();
                                            } else if (BINARY_FORMAT.equals(formatId)) {
                                                formattedResult = Integer.toBinaryString(intResult);
                                                StringBuffer prefix = new StringBuffer("0b");
                                                for (int i = 0; i < 32 - formattedResult.length(); i++) {
                                                    prefix.append('0');
                                                }
                                                prefix.append(formattedResult);
                                                formattedResult = prefix.toString();
                                            } else if (DECIMAL_FORMAT.equals(formatId)) {
                                                formattedResult = Integer.toString(intResult);                                                
                                            } else {
                                                PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid format");
                                            }
                                            rm.setData(new FormattedValueDMData(formattedResult));
                                            rm.done();
                                        } catch (NumberFormatException e) {
                                            PDAPlugin.failRequest(rm, REQUEST_FAILED, "Cannot format value");
                                        }
                                    }
                                }
                            }); 
                    }
                });
        } else {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid expression context " + formattedCtx);
        }
    }

    
    public void writeExpression(final IExpressionDMContext exprCtx, final String exprValue, String formatId, 
        final RequestMonitor rm) 
    {
        writeExpression(exprCtx, exprValue, formatId, true, rm);
    }
    
    /**
     * Method to write an expression, with an additional parameter to suppress
     * issuing of the expression changed event. 
     * @see IExpressions#writeExpression(org.eclipse.cdt.dsf.debug.service.IExpressions.IExpressionDMContext, String, String, RequestMonitor)
     */
    public void writeExpression(final IExpressionDMContext exprCtx, String formattedExprValue, String formatId, 
        final boolean sendEvent, final RequestMonitor rm) 
    {
        String value = null;
        try {
            int intValue = 0;
            if (HEX_FORMAT.equals(formatId)) {
                if (formattedExprValue.startsWith("0x")) formattedExprValue = formattedExprValue.substring(2); 
                value = Integer.toString( Integer.parseInt(formattedExprValue, 16) );
            } else if (DECIMAL_FORMAT.equals(formatId)) {
                value = Integer.toString( Integer.parseInt(formattedExprValue, 10) );
            } else if (OCTAL_FORMAT.equals(formatId)) {
                if (formattedExprValue.startsWith("0c")) formattedExprValue = formattedExprValue.substring(2); 
                value = Integer.toString( Integer.parseInt(formattedExprValue, 8) );
            } else if (BINARY_FORMAT.equals(formatId)) {
                if (formattedExprValue.startsWith("0b")) formattedExprValue = formattedExprValue.substring(2); 
                value = Integer.toString( Integer.parseInt(formattedExprValue, 2) ); 
            }
        } catch (NumberFormatException e) {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Value not formatted properly");
            return;
        }
        
        final String exprValue = value != null ? value : formattedExprValue;
        
        
        if (exprCtx instanceof ExpressionDMContext) {
            final PDAThreadDMContext threadCtx = DMContexts.getAncestorOfType(exprCtx, PDAThreadDMContext.class);
            final IFrameDMContext frameCtx = DMContexts.getAncestorOfType(exprCtx, IFrameDMContext.class);
            
            // Similarly to retrieving the variable, retrieve the 
            // stack depth first.
            fStack.getStackDepth(
                frameCtx, 0,
                new DataRequestMonitor<Integer>(getExecutor(), rm) {
                    @Override
                    protected void handleSuccess() {
                        // Calculate the frame index.
                        int frameId = getData() - frameCtx.getLevel() - 1;
                        
                        // Send the "write" command to PDA debugger
                        fCommandCache.execute(
                            new PDASetVarCommand( threadCtx, frameId, exprCtx.getExpression(), exprValue), 
                            new DataRequestMonitor<PDACommandResult>(getExecutor(), rm) {
                                @Override
                                protected void handleSuccess() {
                                    if (sendEvent) {
                                        getSession().dispatchEvent(new ExpressionChangedDMEvent(exprCtx), getProperties());
                                    }
                                    // An expression changed, clear the cache corresponding to 
                                    // this event.  Since the var evaluate commands, use the thread
                                    // context, we have to clear all the cache entries for that thread.
                                    fCommandCache.reset(DMContexts.getAncestorOfType(exprCtx, PDAThreadDMContext.class));
                                    rm.done();
                                }
                            });
                    }
                });
        } else {
            PDAPlugin.failRequest(rm, INVALID_HANDLE, "Invalid expression context " + exprCtx);
        }
    }

    @DsfServiceEventHandler 
    public void eventDispatched(IResumedDMEvent e) {
        // Mark the cache as not available, so that data retrieval commands 
        // will fail.  Also reset the cache unless it was a step command.
        fCommandCache.setContextAvailable(e.getDMContext(), false);
        if (!e.getReason().equals(StateChangeReason.STEP)) {
            fCommandCache.reset(e.getDMContext());
        }
    }    


    @DsfServiceEventHandler 
    public void eventDispatched(ISuspendedDMEvent e) {
        // Enable sending commands to target and clear the cache.
        fCommandCache.setContextAvailable(e.getDMContext(), true);
        fCommandCache.reset(e.getDMContext());
    }
    
    @DsfServiceEventHandler 
    public void eventDispatched(ExpressionChangedDMEvent e) {
        // An expression changed, clear the cache corresponding to 
        // this event.  Since the var evaluate commands, use the thread
        // context, we have to clear all the cache entries for that thread.
        fCommandCache.reset(DMContexts.getAncestorOfType(e.getDMContext(), PDAThreadDMContext.class));
    }    

    public void flushCache(IDMContext context) {
        fCommandCache.reset(context);
    }
}

Back to the top