1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "Logging.h"
8 
9 #include "LocalAccessible-inl.h"
10 #include "AccEvent.h"
11 #include "DocAccessible.h"
12 #include "nsAccessibilityService.h"
13 #include "nsCoreUtils.h"
14 #include "OuterDocAccessible.h"
15 
16 #include "nsDocShellLoadTypes.h"
17 #include "nsIChannel.h"
18 #include "nsIInterfaceRequestorUtils.h"
19 #include "nsIWebProgress.h"
20 #include "prenv.h"
21 #include "nsIDocShellTreeItem.h"
22 #include "mozilla/PresShell.h"
23 #include "mozilla/StackWalk.h"
24 #include "mozilla/dom/BorrowedAttrInfo.h"
25 #include "mozilla/dom/Document.h"
26 #include "mozilla/dom/Element.h"
27 #include "mozilla/dom/HTMLBodyElement.h"
28 #include "mozilla/dom/Selection.h"
29 
30 using namespace mozilla;
31 using namespace mozilla::a11y;
32 
33 using mozilla::dom::BorrowedAttrInfo;
34 
35 MOZ_DEFINE_MALLOC_SIZE_OF(AccessibleLoggingMallocSizeOf)
36 
37 ////////////////////////////////////////////////////////////////////////////////
38 // Logging helpers
39 
40 static uint32_t sModules = 0;
41 
42 struct ModuleRep {
43   const char* mStr;
44   logging::EModules mModule;
45 };
46 
47 static ModuleRep sModuleMap[] = {{"docload", logging::eDocLoad},
48                                  {"doccreate", logging::eDocCreate},
49                                  {"docdestroy", logging::eDocDestroy},
50                                  {"doclifecycle", logging::eDocLifeCycle},
51 
52                                  {"events", logging::eEvents},
53                                  {"eventTree", logging::eEventTree},
54                                  {"platforms", logging::ePlatforms},
55                                  {"text", logging::eText},
56                                  {"tree", logging::eTree},
57                                  {"treeSize", logging::eTreeSize},
58 
59                                  {"DOMEvents", logging::eDOMEvents},
60                                  {"focus", logging::eFocus},
61                                  {"selection", logging::eSelection},
62                                  {"notifications", logging::eNotifications},
63 
64                                  {"stack", logging::eStack},
65                                  {"verbose", logging::eVerbose}};
66 
EnableLogging(const char * aModulesStr)67 static void EnableLogging(const char* aModulesStr) {
68   sModules = 0;
69   if (!aModulesStr) return;
70 
71   const char* token = aModulesStr;
72   while (*token != '\0') {
73     size_t tokenLen = strcspn(token, ",");
74     for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) {
75       if (strncmp(token, sModuleMap[idx].mStr, tokenLen) == 0) {
76 #if !defined(MOZ_PROFILING) && (!defined(DEBUG) || defined(MOZ_OPTIMIZE))
77         // Stack tracing on profiling enabled or debug not optimized builds.
78         if (strncmp(token, "stack", tokenLen) == 0) break;
79 #endif
80         sModules |= sModuleMap[idx].mModule;
81         printf("\n\nmodule enabled: %s\n", sModuleMap[idx].mStr);
82         break;
83       }
84     }
85     token += tokenLen;
86 
87     if (*token == ',') token++;  // skip ',' char
88   }
89 }
90 
LogDocURI(dom::Document * aDocumentNode)91 static void LogDocURI(dom::Document* aDocumentNode) {
92   printf("uri: %s", aDocumentNode->GetDocumentURI()->GetSpecOrDefault().get());
93 }
94 
LogDocShellState(dom::Document * aDocumentNode)95 static void LogDocShellState(dom::Document* aDocumentNode) {
96   printf("docshell busy: ");
97 
98   nsAutoCString docShellBusy;
99   nsCOMPtr<nsIDocShell> docShell = aDocumentNode->GetDocShell();
100   nsIDocShell::BusyFlags busyFlags = nsIDocShell::BUSY_FLAGS_NONE;
101   docShell->GetBusyFlags(&busyFlags);
102   if (busyFlags == nsIDocShell::BUSY_FLAGS_NONE) {
103     printf("'none'");
104   }
105   if (busyFlags & nsIDocShell::BUSY_FLAGS_BUSY) {
106     printf("'busy'");
107   }
108   if (busyFlags & nsIDocShell::BUSY_FLAGS_BEFORE_PAGE_LOAD) {
109     printf(", 'before page load'");
110   }
111   if (busyFlags & nsIDocShell::BUSY_FLAGS_PAGE_LOADING) {
112     printf(", 'page loading'");
113   }
114 }
115 
LogDocType(dom::Document * aDocumentNode)116 static void LogDocType(dom::Document* aDocumentNode) {
117   if (aDocumentNode->IsActive()) {
118     bool isContent = nsCoreUtils::IsContentDocument(aDocumentNode);
119     printf("%s document", (isContent ? "content" : "chrome"));
120   } else {
121     printf("document type: [failed]");
122   }
123 }
124 
LogDocShellTree(dom::Document * aDocumentNode)125 static void LogDocShellTree(dom::Document* aDocumentNode) {
126   if (aDocumentNode->IsActive()) {
127     nsCOMPtr<nsIDocShellTreeItem> treeItem(aDocumentNode->GetDocShell());
128     nsCOMPtr<nsIDocShellTreeItem> parentTreeItem;
129     treeItem->GetInProcessParent(getter_AddRefs(parentTreeItem));
130     nsCOMPtr<nsIDocShellTreeItem> rootTreeItem;
131     treeItem->GetInProcessRootTreeItem(getter_AddRefs(rootTreeItem));
132     printf(
133         "in-process docshell hierarchy, parent: %p, root: %p, "
134         "is top level: %s;",
135         static_cast<void*>(parentTreeItem), static_cast<void*>(rootTreeItem),
136         (nsCoreUtils::IsTopLevelContentDocInProcess(aDocumentNode) ? "yes"
137                                                                    : "no"));
138   }
139 }
140 
LogDocState(dom::Document * aDocumentNode)141 static void LogDocState(dom::Document* aDocumentNode) {
142   const char* docState = nullptr;
143   dom::Document::ReadyState docStateFlag = aDocumentNode->GetReadyStateEnum();
144   switch (docStateFlag) {
145     case dom::Document::READYSTATE_UNINITIALIZED:
146       docState = "uninitialized";
147       break;
148     case dom::Document::READYSTATE_LOADING:
149       docState = "loading";
150       break;
151     case dom::Document::READYSTATE_INTERACTIVE:
152       docState = "interactive";
153       break;
154     case dom::Document::READYSTATE_COMPLETE:
155       docState = "complete";
156       break;
157   }
158 
159   printf("doc state: %s", docState);
160   printf(", %sinitial", aDocumentNode->IsInitialDocument() ? "" : "not ");
161   printf(", %sshowing", aDocumentNode->IsShowing() ? "" : "not ");
162   printf(", %svisible", aDocumentNode->IsVisible() ? "" : "not ");
163   printf(
164       ", %svisible considering ancestors",
165       nsCoreUtils::IsDocumentVisibleConsideringInProcessAncestors(aDocumentNode)
166           ? ""
167           : "not ");
168   printf(", %sactive", aDocumentNode->IsActive() ? "" : "not ");
169   printf(", %sresource", aDocumentNode->IsResourceDoc() ? "" : "not ");
170 
171   dom::Element* rootEl = aDocumentNode->GetBodyElement();
172   if (!rootEl) {
173     rootEl = aDocumentNode->GetRootElement();
174   }
175   printf(", has %srole content", rootEl ? "" : "no ");
176 }
177 
LogPresShell(dom::Document * aDocumentNode)178 static void LogPresShell(dom::Document* aDocumentNode) {
179   PresShell* presShell = aDocumentNode->GetPresShell();
180   printf("presshell: %p", static_cast<void*>(presShell));
181 
182   nsIScrollableFrame* sf = nullptr;
183   if (presShell) {
184     printf(", is %s destroying", (presShell->IsDestroying() ? "" : "not"));
185     sf = presShell->GetRootScrollFrameAsScrollable();
186   }
187   printf(", root scroll frame: %p", static_cast<void*>(sf));
188 }
189 
LogDocLoadGroup(dom::Document * aDocumentNode)190 static void LogDocLoadGroup(dom::Document* aDocumentNode) {
191   nsCOMPtr<nsILoadGroup> loadGroup = aDocumentNode->GetDocumentLoadGroup();
192   printf("load group: %p", static_cast<void*>(loadGroup));
193 }
194 
LogDocParent(dom::Document * aDocumentNode)195 static void LogDocParent(dom::Document* aDocumentNode) {
196   dom::Document* parentDoc = aDocumentNode->GetInProcessParentDocument();
197   printf("parent DOM document: %p", static_cast<void*>(parentDoc));
198   if (parentDoc) {
199     printf(", parent acc document: %p",
200            static_cast<void*>(GetExistingDocAccessible(parentDoc)));
201     printf("\n    parent ");
202     LogDocURI(parentDoc);
203     printf("\n");
204   }
205 }
206 
LogDocInfo(dom::Document * aDocumentNode,DocAccessible * aDocument)207 static void LogDocInfo(dom::Document* aDocumentNode, DocAccessible* aDocument) {
208   printf("    DOM document: %p, acc document: %p\n    ",
209          static_cast<void*>(aDocumentNode), static_cast<void*>(aDocument));
210 
211   // log document info
212   if (aDocumentNode) {
213     LogDocURI(aDocumentNode);
214     printf("\n    ");
215     LogDocShellState(aDocumentNode);
216     printf("; ");
217     LogDocType(aDocumentNode);
218     printf("\n    ");
219     LogDocShellTree(aDocumentNode);
220     printf("\n    ");
221     LogDocState(aDocumentNode);
222     printf("\n    ");
223     LogPresShell(aDocumentNode);
224     printf("\n    ");
225     LogDocLoadGroup(aDocumentNode);
226     printf(", ");
227     LogDocParent(aDocumentNode);
228     printf("\n");
229   }
230 }
231 
LogShellLoadType(nsIDocShell * aDocShell)232 static void LogShellLoadType(nsIDocShell* aDocShell) {
233   printf("load type: ");
234 
235   uint32_t loadType = 0;
236   aDocShell->GetLoadType(&loadType);
237   switch (loadType) {
238     case LOAD_NORMAL:
239       printf("normal; ");
240       break;
241     case LOAD_NORMAL_REPLACE:
242       printf("normal replace; ");
243       break;
244     case LOAD_HISTORY:
245       printf("history; ");
246       break;
247     case LOAD_NORMAL_BYPASS_CACHE:
248       printf("normal bypass cache; ");
249       break;
250     case LOAD_NORMAL_BYPASS_PROXY:
251       printf("normal bypass proxy; ");
252       break;
253     case LOAD_NORMAL_BYPASS_PROXY_AND_CACHE:
254       printf("normal bypass proxy and cache; ");
255       break;
256     case LOAD_RELOAD_NORMAL:
257       printf("reload normal; ");
258       break;
259     case LOAD_RELOAD_BYPASS_CACHE:
260       printf("reload bypass cache; ");
261       break;
262     case LOAD_RELOAD_BYPASS_PROXY:
263       printf("reload bypass proxy; ");
264       break;
265     case LOAD_RELOAD_BYPASS_PROXY_AND_CACHE:
266       printf("reload bypass proxy and cache; ");
267       break;
268     case LOAD_LINK:
269       printf("link; ");
270       break;
271     case LOAD_REFRESH:
272       printf("refresh; ");
273       break;
274     case LOAD_REFRESH_REPLACE:
275       printf("refresh replace; ");
276       break;
277     case LOAD_RELOAD_CHARSET_CHANGE:
278       printf("reload charset change; ");
279       break;
280     case LOAD_BYPASS_HISTORY:
281       printf("bypass history; ");
282       break;
283     case LOAD_STOP_CONTENT:
284       printf("stop content; ");
285       break;
286     case LOAD_STOP_CONTENT_AND_REPLACE:
287       printf("stop content and replace; ");
288       break;
289     case LOAD_PUSHSTATE:
290       printf("load pushstate; ");
291       break;
292     case LOAD_REPLACE_BYPASS_CACHE:
293       printf("replace bypass cache; ");
294       break;
295     case LOAD_ERROR_PAGE:
296       printf("error page;");
297       break;
298     default:
299       printf("unknown");
300   }
301 }
302 
LogRequest(nsIRequest * aRequest)303 static void LogRequest(nsIRequest* aRequest) {
304   if (aRequest) {
305     nsAutoCString name;
306     aRequest->GetName(name);
307     printf("    request spec: %s\n", name.get());
308     uint32_t loadFlags = 0;
309     aRequest->GetLoadFlags(&loadFlags);
310     printf("    request load flags: %x; ", loadFlags);
311     if (loadFlags & nsIChannel::LOAD_DOCUMENT_URI) printf("document uri; ");
312     if (loadFlags & nsIChannel::LOAD_RETARGETED_DOCUMENT_URI) {
313       printf("retargeted document uri; ");
314     }
315     if (loadFlags & nsIChannel::LOAD_REPLACE) printf("replace; ");
316     if (loadFlags & nsIChannel::LOAD_INITIAL_DOCUMENT_URI) {
317       printf("initial document uri; ");
318     }
319     if (loadFlags & nsIChannel::LOAD_TARGETED) printf("targeted; ");
320     if (loadFlags & nsIChannel::LOAD_CALL_CONTENT_SNIFFERS) {
321       printf("call content sniffers; ");
322     }
323     if (loadFlags & nsIChannel::LOAD_BYPASS_URL_CLASSIFIER) {
324       printf("bypass classify uri; ");
325     }
326   } else {
327     printf("    no request");
328   }
329 }
330 
LogDocAccState(DocAccessible * aDocument)331 static void LogDocAccState(DocAccessible* aDocument) {
332   printf("document acc state: ");
333   if (aDocument->HasLoadState(DocAccessible::eCompletelyLoaded)) {
334     printf("completely loaded;");
335   } else if (aDocument->HasLoadState(DocAccessible::eReady)) {
336     printf("ready;");
337   } else if (aDocument->HasLoadState(DocAccessible::eDOMLoaded)) {
338     printf("DOM loaded;");
339   } else if (aDocument->HasLoadState(DocAccessible::eTreeConstructed)) {
340     printf("tree constructed;");
341   }
342 }
343 
GetDocLoadEventType(AccEvent * aEvent,nsACString & aEventType)344 static void GetDocLoadEventType(AccEvent* aEvent, nsACString& aEventType) {
345   uint32_t type = aEvent->GetEventType();
346   if (type == nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_STOPPED) {
347     aEventType.AssignLiteral("load stopped");
348   } else if (type == nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE) {
349     aEventType.AssignLiteral("load complete");
350   } else if (type == nsIAccessibleEvent::EVENT_DOCUMENT_RELOAD) {
351     aEventType.AssignLiteral("reload");
352   } else if (type == nsIAccessibleEvent::EVENT_STATE_CHANGE) {
353     AccStateChangeEvent* event = downcast_accEvent(aEvent);
354     if (event->GetState() == states::BUSY) {
355       aEventType.AssignLiteral("busy ");
356       if (event->IsStateEnabled()) {
357         aEventType.AppendLiteral("true");
358       } else {
359         aEventType.AppendLiteral("false");
360       }
361     }
362   }
363 }
364 
DescribeNode(nsINode * aNode,nsAString & aOutDescription)365 static void DescribeNode(nsINode* aNode, nsAString& aOutDescription) {
366   if (!aNode) {
367     aOutDescription.AppendLiteral("null");
368     return;
369   }
370 
371   aOutDescription.AppendPrintf("0x%p, ", (void*)aNode);
372   aOutDescription.Append(aNode->NodeInfo()->QualifiedName());
373 
374   if (!aNode->IsElement()) {
375     return;
376   }
377 
378   dom::Element* elm = aNode->AsElement();
379 
380   nsAtom* idAtom = elm->GetID();
381   if (idAtom) {
382     nsAutoCString id;
383     idAtom->ToUTF8String(id);
384     aOutDescription.AppendPrintf("@id=\"%s\" ", id.get());
385   } else {
386     aOutDescription.Append(' ');
387   }
388 
389   uint32_t attrCount = elm->GetAttrCount();
390   if (!attrCount || (idAtom && attrCount == 1)) {
391     return;
392   }
393 
394   aOutDescription.AppendLiteral("[ ");
395 
396   for (uint32_t index = 0; index < attrCount; index++) {
397     BorrowedAttrInfo info = elm->GetAttrInfoAt(index);
398 
399     // Skip redundant display of id attribute.
400     if (info.mName->Equals(nsGkAtoms::id)) {
401       continue;
402     }
403 
404     // name
405     nsAutoString name;
406     info.mName->GetQualifiedName(name);
407     aOutDescription.Append(name);
408 
409     aOutDescription.AppendLiteral("=\"");
410 
411     // value
412     nsAutoString value;
413     info.mValue->ToString(value);
414     for (uint32_t i = value.Length(); i > 0; --i) {
415       if (value[i - 1] == char16_t('"')) value.Insert(char16_t('\\'), i - 1);
416     }
417     aOutDescription.Append(value);
418     aOutDescription.AppendLiteral("\" ");
419   }
420 
421   aOutDescription.Append(']');
422 }
423 
424 ////////////////////////////////////////////////////////////////////////////////
425 // namespace logging:: document life cycle logging methods
426 
427 static const char* sDocLoadTitle = "DOCLOAD";
428 static const char* sDocCreateTitle = "DOCCREATE";
429 static const char* sDocDestroyTitle = "DOCDESTROY";
430 static const char* sDocEventTitle = "DOCEVENT";
431 static const char* sFocusTitle = "FOCUS";
432 
DocLoad(const char * aMsg,nsIWebProgress * aWebProgress,nsIRequest * aRequest,uint32_t aStateFlags)433 void logging::DocLoad(const char* aMsg, nsIWebProgress* aWebProgress,
434                       nsIRequest* aRequest, uint32_t aStateFlags) {
435   MsgBegin(sDocLoadTitle, "%s", aMsg);
436 
437   nsCOMPtr<mozIDOMWindowProxy> DOMWindow;
438   aWebProgress->GetDOMWindow(getter_AddRefs(DOMWindow));
439   nsPIDOMWindowOuter* window = nsPIDOMWindowOuter::From(DOMWindow);
440   if (!window) {
441     MsgEnd();
442     return;
443   }
444 
445   nsCOMPtr<dom::Document> documentNode = window->GetDoc();
446   if (!documentNode) {
447     MsgEnd();
448     return;
449   }
450 
451   DocAccessible* document = GetExistingDocAccessible(documentNode);
452 
453   LogDocInfo(documentNode, document);
454 
455   nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
456   printf("\n    ");
457   LogShellLoadType(docShell);
458   printf("\n");
459   LogRequest(aRequest);
460   printf("\n");
461   printf("    state flags: %x", aStateFlags);
462   bool isDocLoading;
463   aWebProgress->GetIsLoadingDocument(&isDocLoading);
464   printf(", document is %sloading\n", (isDocLoading ? "" : "not "));
465 
466   MsgEnd();
467 }
468 
DocLoad(const char * aMsg,dom::Document * aDocumentNode)469 void logging::DocLoad(const char* aMsg, dom::Document* aDocumentNode) {
470   MsgBegin(sDocLoadTitle, "%s", aMsg);
471 
472   DocAccessible* document = GetExistingDocAccessible(aDocumentNode);
473   LogDocInfo(aDocumentNode, document);
474 
475   MsgEnd();
476 }
477 
DocCompleteLoad(DocAccessible * aDocument,bool aIsLoadEventTarget)478 void logging::DocCompleteLoad(DocAccessible* aDocument,
479                               bool aIsLoadEventTarget) {
480   MsgBegin(sDocLoadTitle, "document loaded *completely*");
481 
482   printf("    DOM document: %p, acc document: %p\n",
483          static_cast<void*>(aDocument->DocumentNode()),
484          static_cast<void*>(aDocument));
485 
486   printf("    ");
487   LogDocURI(aDocument->DocumentNode());
488   printf("\n");
489 
490   printf("    ");
491   LogDocAccState(aDocument);
492   printf("\n");
493 
494   printf("    document is load event target: %s\n",
495          (aIsLoadEventTarget ? "true" : "false"));
496 
497   MsgEnd();
498 }
499 
DocLoadEventFired(AccEvent * aEvent)500 void logging::DocLoadEventFired(AccEvent* aEvent) {
501   nsAutoCString strEventType;
502   GetDocLoadEventType(aEvent, strEventType);
503   if (!strEventType.IsEmpty()) printf("  fire: %s\n", strEventType.get());
504 }
505 
DocLoadEventHandled(AccEvent * aEvent)506 void logging::DocLoadEventHandled(AccEvent* aEvent) {
507   nsAutoCString strEventType;
508   GetDocLoadEventType(aEvent, strEventType);
509   if (strEventType.IsEmpty()) return;
510 
511   MsgBegin(sDocEventTitle, "handled '%s' event", strEventType.get());
512 
513   DocAccessible* document = aEvent->GetAccessible()->AsDoc();
514   if (document) LogDocInfo(document->DocumentNode(), document);
515 
516   MsgEnd();
517 }
518 
DocCreate(const char * aMsg,dom::Document * aDocumentNode,DocAccessible * aDocument)519 void logging::DocCreate(const char* aMsg, dom::Document* aDocumentNode,
520                         DocAccessible* aDocument) {
521   DocAccessible* document =
522       aDocument ? aDocument : GetExistingDocAccessible(aDocumentNode);
523 
524   MsgBegin(sDocCreateTitle, "%s", aMsg);
525   LogDocInfo(aDocumentNode, document);
526   MsgEnd();
527 }
528 
DocDestroy(const char * aMsg,dom::Document * aDocumentNode,DocAccessible * aDocument)529 void logging::DocDestroy(const char* aMsg, dom::Document* aDocumentNode,
530                          DocAccessible* aDocument) {
531   DocAccessible* document =
532       aDocument ? aDocument : GetExistingDocAccessible(aDocumentNode);
533 
534   MsgBegin(sDocDestroyTitle, "%s", aMsg);
535   LogDocInfo(aDocumentNode, document);
536   MsgEnd();
537 }
538 
OuterDocDestroy(OuterDocAccessible * aOuterDoc)539 void logging::OuterDocDestroy(OuterDocAccessible* aOuterDoc) {
540   MsgBegin(sDocDestroyTitle, "outerdoc shutdown");
541   logging::Address("outerdoc", aOuterDoc);
542   MsgEnd();
543 }
544 
FocusNotificationTarget(const char * aMsg,const char * aTargetDescr,LocalAccessible * aTarget)545 void logging::FocusNotificationTarget(const char* aMsg,
546                                       const char* aTargetDescr,
547                                       LocalAccessible* aTarget) {
548   MsgBegin(sFocusTitle, "%s", aMsg);
549   AccessibleNNode(aTargetDescr, aTarget);
550   MsgEnd();
551 }
552 
FocusNotificationTarget(const char * aMsg,const char * aTargetDescr,nsINode * aTargetNode)553 void logging::FocusNotificationTarget(const char* aMsg,
554                                       const char* aTargetDescr,
555                                       nsINode* aTargetNode) {
556   MsgBegin(sFocusTitle, "%s", aMsg);
557   Node(aTargetDescr, aTargetNode);
558   MsgEnd();
559 }
560 
FocusNotificationTarget(const char * aMsg,const char * aTargetDescr,nsISupports * aTargetThing)561 void logging::FocusNotificationTarget(const char* aMsg,
562                                       const char* aTargetDescr,
563                                       nsISupports* aTargetThing) {
564   MsgBegin(sFocusTitle, "%s", aMsg);
565 
566   if (aTargetThing) {
567     nsCOMPtr<nsINode> targetNode(do_QueryInterface(aTargetThing));
568     if (targetNode) {
569       AccessibleNNode(aTargetDescr, targetNode);
570     } else {
571       printf("    %s: %p, window\n", aTargetDescr,
572              static_cast<void*>(aTargetThing));
573     }
574   }
575 
576   MsgEnd();
577 }
578 
ActiveItemChangeCausedBy(const char * aCause,LocalAccessible * aTarget)579 void logging::ActiveItemChangeCausedBy(const char* aCause,
580                                        LocalAccessible* aTarget) {
581   SubMsgBegin();
582   printf("    Caused by: %s\n", aCause);
583   AccessibleNNode("Item", aTarget);
584   SubMsgEnd();
585 }
586 
ActiveWidget(LocalAccessible * aWidget)587 void logging::ActiveWidget(LocalAccessible* aWidget) {
588   SubMsgBegin();
589 
590   AccessibleNNode("Widget", aWidget);
591   printf("    Widget is active: %s, has operable items: %s\n",
592          (aWidget && aWidget->IsActiveWidget() ? "true" : "false"),
593          (aWidget && aWidget->AreItemsOperable() ? "true" : "false"));
594 
595   SubMsgEnd();
596 }
597 
FocusDispatched(LocalAccessible * aTarget)598 void logging::FocusDispatched(LocalAccessible* aTarget) {
599   SubMsgBegin();
600   AccessibleNNode("A11y target", aTarget);
601   SubMsgEnd();
602 }
603 
SelChange(dom::Selection * aSelection,DocAccessible * aDocument,int16_t aReason)604 void logging::SelChange(dom::Selection* aSelection, DocAccessible* aDocument,
605                         int16_t aReason) {
606   SelectionType type = aSelection->GetType();
607 
608   const char* strType = 0;
609   if (type == SelectionType::eNormal) {
610     strType = "normal";
611   } else if (type == SelectionType::eSpellCheck) {
612     strType = "spellcheck";
613   } else {
614     strType = "unknown";
615   }
616 
617   bool isIgnored = !aDocument || !aDocument->IsContentLoaded();
618   printf(
619       "\nSelection changed, selection type: %s, notification %s, reason: %d\n",
620       strType, (isIgnored ? "ignored" : "pending"), aReason);
621 
622   Stack();
623 }
624 
TreeInfo(const char * aMsg,uint32_t aExtraFlags,...)625 void logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags, ...) {
626   if (IsEnabledAll(logging::eTree | aExtraFlags)) {
627     va_list vl;
628     va_start(vl, aExtraFlags);
629     const char* descr = va_arg(vl, const char*);
630     if (descr) {
631       LocalAccessible* acc = va_arg(vl, LocalAccessible*);
632       MsgBegin("TREE", "%s; doc: %p", aMsg, acc ? acc->Document() : nullptr);
633       AccessibleInfo(descr, acc);
634       while ((descr = va_arg(vl, const char*))) {
635         AccessibleInfo(descr, va_arg(vl, LocalAccessible*));
636       }
637     } else {
638       MsgBegin("TREE", "%s", aMsg);
639     }
640     va_end(vl);
641     MsgEnd();
642 
643     if (aExtraFlags & eStack) {
644       Stack();
645     }
646   }
647 }
648 
TreeInfo(const char * aMsg,uint32_t aExtraFlags,const char * aMsg1,LocalAccessible * aAcc,const char * aMsg2,nsINode * aNode)649 void logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags,
650                        const char* aMsg1, LocalAccessible* aAcc,
651                        const char* aMsg2, nsINode* aNode) {
652   if (IsEnabledAll(logging::eTree | aExtraFlags)) {
653     MsgBegin("TREE", "%s; doc: %p", aMsg, aAcc ? aAcc->Document() : nullptr);
654     AccessibleInfo(aMsg1, aAcc);
655     LocalAccessible* acc =
656         aAcc ? aAcc->Document()->GetAccessible(aNode) : nullptr;
657     if (acc) {
658       AccessibleInfo(aMsg2, acc);
659     } else {
660       Node(aMsg2, aNode);
661     }
662     MsgEnd();
663   }
664 }
665 
TreeInfo(const char * aMsg,uint32_t aExtraFlags,LocalAccessible * aParent)666 void logging::TreeInfo(const char* aMsg, uint32_t aExtraFlags,
667                        LocalAccessible* aParent) {
668   if (IsEnabledAll(logging::eTree | aExtraFlags)) {
669     MsgBegin("TREE", "%s; doc: %p", aMsg, aParent->Document());
670     AccessibleInfo("container", aParent);
671     for (uint32_t idx = 0; idx < aParent->ChildCount(); idx++) {
672       AccessibleInfo("child", aParent->LocalChildAt(idx));
673     }
674     MsgEnd();
675   }
676 }
677 
Tree(const char * aTitle,const char * aMsgText,LocalAccessible * aRoot,GetTreePrefix aPrefixFunc,void * aGetTreePrefixData)678 void logging::Tree(const char* aTitle, const char* aMsgText,
679                    LocalAccessible* aRoot, GetTreePrefix aPrefixFunc,
680                    void* aGetTreePrefixData) {
681   logging::MsgBegin(aTitle, "%s", aMsgText);
682 
683   nsAutoString level;
684   LocalAccessible* root = aRoot;
685   do {
686     const char* prefix =
687         aPrefixFunc ? aPrefixFunc(aGetTreePrefixData, root) : "";
688     printf("%s", NS_ConvertUTF16toUTF8(level).get());
689     logging::AccessibleInfo(prefix, root);
690     if (root->LocalFirstChild() && !root->LocalFirstChild()->IsDoc()) {
691       level.AppendLiteral(u"  ");
692       root = root->LocalFirstChild();
693       continue;
694     }
695     int32_t idxInParent = root != aRoot && root->mParent
696                               ? root->mParent->mChildren.IndexOf(root)
697                               : -1;
698     if (idxInParent != -1 &&
699         idxInParent <
700             static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
701       root = root->mParent->mChildren.ElementAt(idxInParent + 1);
702       continue;
703     }
704     while (root != aRoot && (root = root->LocalParent())) {
705       level.Cut(0, 2);
706       int32_t idxInParent = !root->IsDoc() && root->mParent
707                                 ? root->mParent->mChildren.IndexOf(root)
708                                 : -1;
709       if (idxInParent != -1 &&
710           idxInParent <
711               static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
712         root = root->mParent->mChildren.ElementAt(idxInParent + 1);
713         break;
714       }
715     }
716   } while (root && root != aRoot);
717 
718   logging::MsgEnd();
719 }
720 
DOMTree(const char * aTitle,const char * aMsgText,DocAccessible * aDocument)721 void logging::DOMTree(const char* aTitle, const char* aMsgText,
722                       DocAccessible* aDocument) {
723   logging::MsgBegin(aTitle, "%s", aMsgText);
724   nsAutoString level;
725   nsINode* root = aDocument->DocumentNode();
726   do {
727     printf("%s", NS_ConvertUTF16toUTF8(level).get());
728     logging::Node("", root);
729     if (root->GetFirstChild()) {
730       level.AppendLiteral(u"  ");
731       root = root->GetFirstChild();
732       continue;
733     }
734     if (root->GetNextSibling()) {
735       root = root->GetNextSibling();
736       continue;
737     }
738     while ((root = root->GetParentNode())) {
739       level.Cut(0, 2);
740       if (root->GetNextSibling()) {
741         root = root->GetNextSibling();
742         break;
743       }
744     }
745   } while (root);
746   logging::MsgEnd();
747 }
748 
TreeSize(const char * aTitle,const char * aMsgText,LocalAccessible * aRoot)749 void logging::TreeSize(const char* aTitle, const char* aMsgText,
750                        LocalAccessible* aRoot) {
751   logging::MsgBegin(aTitle, "%s", aMsgText);
752   logging::AccessibleInfo("Logging tree size from: ", aRoot);
753   size_t b = 0;
754   size_t n = 0;
755   LocalAccessible* root = aRoot;
756   do {
757     // Process the current acc
758     b += AccessibleLoggingMallocSizeOf(root);
759     n++;
760 
761     // Get next acc
762     if (root->LocalFirstChild() && !root->LocalFirstChild()->IsDoc()) {
763       root = root->LocalFirstChild();
764       continue;
765     }
766     int32_t idxInParent = root != aRoot && root->mParent
767                               ? root->mParent->mChildren.IndexOf(root)
768                               : -1;
769     if (idxInParent != -1 &&
770         idxInParent <
771             static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
772       root = root->mParent->mChildren.ElementAt(idxInParent + 1);
773       continue;
774     }
775     while (root != aRoot && (root = root->LocalParent())) {
776       int32_t idxInParent = !root->IsDoc() && root->mParent
777                                 ? root->mParent->mChildren.IndexOf(root)
778                                 : -1;
779       if (idxInParent != -1 &&
780           idxInParent <
781               static_cast<int32_t>(root->mParent->mChildren.Length() - 1)) {
782         root = root->mParent->mChildren.ElementAt(idxInParent + 1);
783         break;
784       }
785     }
786   } while (root && root != aRoot);
787 
788   printf("\nTree contains %zu accessibles and is %zu bytes\n", n, b);
789   logging::MsgEnd();
790 }
791 
MsgBegin(const char * aTitle,const char * aMsgText,...)792 void logging::MsgBegin(const char* aTitle, const char* aMsgText, ...) {
793   printf("\nA11Y %s: ", aTitle);
794 
795   va_list argptr;
796   va_start(argptr, aMsgText);
797   vprintf(aMsgText, argptr);
798   va_end(argptr);
799 
800   PRIntervalTime time = PR_IntervalNow();
801   uint32_t mins = (PR_IntervalToSeconds(time) / 60) % 60;
802   uint32_t secs = PR_IntervalToSeconds(time) % 60;
803   uint32_t msecs = PR_IntervalToMilliseconds(time) % 1000;
804   printf("; %02u:%02u.%03u", mins, secs, msecs);
805 
806   printf("\n  {\n");
807 }
808 
MsgEnd()809 void logging::MsgEnd() { printf("  }\n"); }
810 
SubMsgBegin()811 void logging::SubMsgBegin() { printf("  {\n"); }
812 
SubMsgEnd()813 void logging::SubMsgEnd() { printf("  }\n"); }
814 
MsgEntry(const char * aEntryText,...)815 void logging::MsgEntry(const char* aEntryText, ...) {
816   printf("    ");
817 
818   va_list argptr;
819   va_start(argptr, aEntryText);
820   vprintf(aEntryText, argptr);
821   va_end(argptr);
822 
823   printf("\n");
824 }
825 
Text(const char * aText)826 void logging::Text(const char* aText) { printf("  %s\n", aText); }
827 
Address(const char * aDescr,LocalAccessible * aAcc)828 void logging::Address(const char* aDescr, LocalAccessible* aAcc) {
829   if (!aAcc->IsDoc()) {
830     printf("    %s accessible: %p, node: %p\n", aDescr,
831            static_cast<void*>(aAcc), static_cast<void*>(aAcc->GetNode()));
832   }
833 
834   DocAccessible* doc = aAcc->Document();
835   dom::Document* docNode = doc->DocumentNode();
836   printf("    document: %p, node: %p\n", static_cast<void*>(doc),
837          static_cast<void*>(docNode));
838 
839   printf("    ");
840   LogDocURI(docNode);
841   printf("\n");
842 }
843 
Node(const char * aDescr,nsINode * aNode)844 void logging::Node(const char* aDescr, nsINode* aNode) {
845   nsINode* parentNode = aNode ? aNode->GetParentNode() : nullptr;
846   int32_t idxInParent = parentNode ? parentNode->ComputeIndexOf(aNode) : -1;
847 
848   nsAutoString nodeDesc;
849   DescribeNode(aNode, nodeDesc);
850   printf("    %s: %s, idx in parent %d\n", aDescr,
851          NS_ConvertUTF16toUTF8(nodeDesc).get(), idxInParent);
852 }
853 
Document(DocAccessible * aDocument)854 void logging::Document(DocAccessible* aDocument) {
855   printf("    Document: %p, document node: %p\n", static_cast<void*>(aDocument),
856          static_cast<void*>(aDocument->DocumentNode()));
857 
858   printf("    Document ");
859   LogDocURI(aDocument->DocumentNode());
860   printf("\n");
861 }
862 
AccessibleInfo(const char * aDescr,LocalAccessible * aAccessible)863 void logging::AccessibleInfo(const char* aDescr, LocalAccessible* aAccessible) {
864   printf("    %s: %p; ", aDescr, static_cast<void*>(aAccessible));
865   if (!aAccessible) {
866     printf("\n");
867     return;
868   }
869   if (aAccessible->IsDefunct()) {
870     printf("defunct\n");
871     return;
872   }
873   if (!aAccessible->Document() || aAccessible->Document()->IsDefunct()) {
874     printf("document is shutting down, no info\n");
875     return;
876   }
877 
878   nsAutoString role;
879   GetAccService()->GetStringRole(aAccessible->Role(), role);
880   printf("role: %s", NS_ConvertUTF16toUTF8(role).get());
881 
882   nsAutoString name;
883   aAccessible->Name(name);
884   if (!name.IsEmpty()) {
885     printf(", name: '%s'", NS_ConvertUTF16toUTF8(name).get());
886   }
887 
888   printf(", idx: %d", aAccessible->IndexInParent());
889 
890   nsAutoString nodeDesc;
891   DescribeNode(aAccessible->GetNode(), nodeDesc);
892   printf(", node: %s\n", NS_ConvertUTF16toUTF8(nodeDesc).get());
893 }
894 
AccessibleNNode(const char * aDescr,LocalAccessible * aAccessible)895 void logging::AccessibleNNode(const char* aDescr,
896                               LocalAccessible* aAccessible) {
897   printf("    %s: %p; ", aDescr, static_cast<void*>(aAccessible));
898   if (!aAccessible) return;
899 
900   nsAutoString role;
901   GetAccService()->GetStringRole(aAccessible->Role(), role);
902   nsAutoString name;
903   aAccessible->Name(name);
904 
905   printf("role: %s, name: '%s';\n", NS_ConvertUTF16toUTF8(role).get(),
906          NS_ConvertUTF16toUTF8(name).get());
907 
908   nsAutoCString nodeDescr(aDescr);
909   nodeDescr.AppendLiteral(" node");
910   Node(nodeDescr.get(), aAccessible->GetNode());
911 
912   Document(aAccessible->Document());
913 }
914 
AccessibleNNode(const char * aDescr,nsINode * aNode)915 void logging::AccessibleNNode(const char* aDescr, nsINode* aNode) {
916   DocAccessible* document =
917       GetAccService()->GetDocAccessible(aNode->OwnerDoc());
918 
919   if (document) {
920     LocalAccessible* accessible = document->GetAccessible(aNode);
921     if (accessible) {
922       AccessibleNNode(aDescr, accessible);
923       return;
924     }
925   }
926 
927   nsAutoCString nodeDescr("[not accessible] ");
928   nodeDescr.Append(aDescr);
929   Node(nodeDescr.get(), aNode);
930 
931   if (document) {
932     Document(document);
933     return;
934   }
935 
936   printf("    [contained by not accessible document]:\n");
937   LogDocInfo(aNode->OwnerDoc(), document);
938   printf("\n");
939 }
940 
DOMEvent(const char * aDescr,nsINode * aOrigTarget,const nsAString & aEventType)941 void logging::DOMEvent(const char* aDescr, nsINode* aOrigTarget,
942                        const nsAString& aEventType) {
943   logging::MsgBegin("DOMEvents", "event '%s' %s",
944                     NS_ConvertUTF16toUTF8(aEventType).get(), aDescr);
945   logging::AccessibleNNode("Target", aOrigTarget);
946   logging::MsgEnd();
947 }
948 
Stack()949 void logging::Stack() {
950   if (IsEnabled(eStack)) {
951     printf("  stack: \n");
952     MozWalkTheStack(stdout);
953   }
954 }
955 
956 ////////////////////////////////////////////////////////////////////////////////
957 // namespace logging:: initialization
958 
IsEnabled(uint32_t aModules)959 bool logging::IsEnabled(uint32_t aModules) { return sModules & aModules; }
960 
IsEnabledAll(uint32_t aModules)961 bool logging::IsEnabledAll(uint32_t aModules) {
962   return (sModules & aModules) == aModules;
963 }
964 
IsEnabled(const nsAString & aModuleStr)965 bool logging::IsEnabled(const nsAString& aModuleStr) {
966   for (unsigned int idx = 0; idx < ArrayLength(sModuleMap); idx++) {
967     if (aModuleStr.EqualsASCII(sModuleMap[idx].mStr)) {
968       return sModules & sModuleMap[idx].mModule;
969     }
970   }
971 
972   return false;
973 }
974 
Enable(const nsCString & aModules)975 void logging::Enable(const nsCString& aModules) {
976   EnableLogging(aModules.get());
977 }
978 
CheckEnv()979 void logging::CheckEnv() { EnableLogging(PR_GetEnv("A11YLOG")); }
980